场景:首先调用发送短信接口,然后调用注册接口,结果后台的session不一致获取不到之前验证码。
实质:每次ajax跨域访问都是新的session ,每次的sessionID都不一样
解决:
package com.runmin.bajie.intercepter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 跨域拦截器
* @author ouyan
*
*/
public class AccessInterceptor implements HandlerInterceptor { @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception { } @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception { } @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setContentType("textml;charset=UTF-8");
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("XDomainRequestAllowed","1");
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Credential", "true");
response.setHeader("P3P", "CP=CAO PSA OUR");
if(request.getHeader("Access-Control-Request-Method")!=null&&"OPTIONS".equals(request.getMethod())) {
response.addHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept");
response.addHeader("Access-Control-Max-age", "120"); }
return true;
} }
详细:
前端JS:
$.ajax({
url: host+url,
type: type,
dataType: 'json',
async: false,
cache: false,
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: params,
success: function(data) {
//回调函数
if (callbackFun) {
callbackFun(data);
}
},
error: function() {}
})