先来说说遇到的问题,在java中写了两个方法,暂且称之为A方法,B方法。 A方法中往session中存session.setAttribute("phoneMa",ma);在A方法中是可以取到phoneMa=session.getAttribute("phoneMa")的值,但是在B方法中获取phoneMa的值 phoneMa= session.getAttribute("phoneMa")一直为null。 百思不得解,然后查看两个方法中的sessionId=session.getId()是否一致,发现真的不一致。 这样,就找到了问题的所在。找资料发现:因为跨域问题SSIONID每次请求都会变化。而我的后台也设置了跨域请求
我的跨域源码是:
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 httpResponse = (HttpServletResponse) servletResponse;
//*表示允许所有域名跨域
httpResponse.addHeader("Access-Control-Allow-Origin", "*");
//允许的请求头类型
httpResponse.addHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
//允许跨域的Http方法
httpResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy() {
}
}
doFilter代码修改之后:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
//*表示允许所有域名跨域
httpResponse.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8020");
httpResponse.addHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
//允许跨域的Http方法
httpResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
httpResponse.addHeader("Access-Control-Max-Age", "0");
httpResponse.addHeader("Access-Control-Allow-Credentials","true");
httpResponse.addHeader("XDomainRequestAllowed","1");
filterChain.doFilter(servletRequest, servletResponse);
}
此时还不算完,需要在前端ajax请求上也要加入响应的代码。
xhrFields: {
withCredentials: true
},
crossDomain: true,
我的ajax请求是这样的:
$.ajax({
type: "post",
url: IP + "member/sendCode",
//加上这句话
xhrFields: {
withCredentials: true
},
crossDomain: true,
data:{
phone:inphone
},
success: function(data) {
console.log(JSON.stringify(data));
if(data.code == 200){
}
}
});
这样再测试的时候,sessionId值是一样的,也能获取session的值了。
此文只作为笔记记录,可能会与其他大神写的内容雷同。 不喜勿喷!