Ajax 跨域请求时sessionId不固定问题解决

当ajax异步跨域访问时,由于浏览器的保护机制,会导致cookie设置的jsessionId不能保存,导致下一次ajax请求时又重复生成sessionid,导致重复要求登录。

问题解决:

java端:

response.setContentType("textml;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "0");
        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");
        response.setHeader("XDomainRequestAllowed","1");

 ajax前端:

在ajax 请求是也要加相应的东西
$.ajax({
url:url,
//加上这句话
xhrFields: {
           withCredentials: true
       },
       crossDomain: true,

success:function(result){
alert("test");
},
error:function(){
}
});

 参考自:http://www.cnblogs.com/renhaisong/p/6892341.html

相关推荐