ajax cross domain problem and cross domain loss seesion problem

Cross domain issues encountered in the project. So record it.

Project A (ajax mode) requests to project B.

1: You need to do some configuration in B to add a filter
My is spring MVC

package net.pt365.cms.api.spring.security;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

 * CorsFileter Function Description: CORS filter
 * @author 
public class CorsFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {


    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//request.getHeader("Origin")
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "0");
        response.setHeader("P3P","CP=CAO PSA OUR");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");

    public void destroy() {


In this way, cross domain can be realized. If you only implement cross domain, there are some unnecessary statements above, but you can write them correctly..
Only such a configuration will cause session loss after cross domain. This is the problem of session inconsistency. The end result is, for example, not logging in,
So, there's ajax configuration.

2: ajax writing in the foreground

var transformurl =""; //Cross domain request
                        method:"post",xhrFields:{withCredentials: true},crossDomain: true,
xhrFields:{withCredentials: true},crossDomain: true,

 response.setHeader("P3P","CP=CAO PSA OUR");//This is the configuration in the filter

These are the two sentences that work for.. It solves the problem of session inconsistency.

Okay. Perfect!

Tags: Session Spring Java

Posted on Thu, 02 Apr 2020 04:34:48 -0700 by wikstov