公司项目中前后端分开开发,前端访问后台接口时产生ajax跨域问题以及每次访问接口时的session都是不一样的问题,记录下来备忘(后台用的jfinal框架,前端用vue开发)
参考 http://blog.csdn.net/qq_27373459/article/details/77099207
创建一个拦截器拦截所有请求 :
public class AjaxIntercepter implements Interceptor {
@Override
public void intercept(Invocation inv) {
HttpServletResponse response = inv.getController().getResponse();
HttpServletRequest request = inv.getController().getRequest();
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,Access-Control-Allow-Headers");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("XDomainRequestAllowed","1");
inv.invoke(); //添加拦截器的 放行方法
}
}
在前端的ajax请求中添加红色代码可解决ajax,session 跨域问题
$.ajax({
url:url,
//加上这句话
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function(result){
alert("test");
},
error:function(){
}
});
这样前端访问后台接口时sessionId 将保持同一个,方便我们将用户信息保存在session中