环境:
前端 vue ip地址:192.168.1.205
后端 springboot2.0 ip地址:192.168.1.217
主要开发后端。
问题:
首先登陆成功时将用户存在session中,后续请求在将用户从session中取出检查。后续请求取出的用户都为null。
解决过程:
首先发现sessionID不一致,导致每一次都是新的会话,当然不可能存在用户了。然后发现cookie浏览器不能自动保存,服务器响应set-cookie了
搜索问题,发现跨域,服务器响应的setCookie浏览器无法保存,而且就算保存了域名不同也不能携带。
第一步:
后台添加过滤器,因为前后端分离,不可能每个方法都写一遍,所以添加过滤器统一处理。
packagecom.test.filter;import javax.servlet.*;importjavax.servlet.annotation.WebFilter;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;
@WebFilter(urlPatterns= "/*", filterName = "CORSFilter")public class CORSFilter implementsFilter {
@Overridepublic voiddestroy() {
}/*** 此过滤器只是处理跨域问题
*@paramservletRequest
*@paramservletResponse
*@paramchain
*@throwsServletException
*@throwsIOException*/@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throwsServletException, IOException {
HttpServletRequest req=(HttpServletRequest) servletRequest;
HttpServletResponse resp=(HttpServletResponse) servletResponse;
String origin= req.getHeader("Origin");if(origin == null) {
origin= req.getHeader("Referer");
}
resp.setHeader("Access-Control-Allow-Origin", origin);//这里不能写*,*代表接受所有域名访问,如写*则下面一行代码无效。谨记
resp.setHeader("Access-Control-Allow-Credentials", "true");//true代表允许携带cookie
chain.doFilter(servletRequest,servletResponse);}
@Overridepublic void init(FilterConfig filterConfig) throwsServletException {
}
}
springboot2.配置过滤器时,启动类必须加上@ServletComponentScan才会加载过滤器
@SpringBootApplication
@EnableTransactionManagement(order= 10)
@ServletComponentScanpublic classApplication {public static voidmain(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后前端配置
使用vue.resource发送请求时配置如下:
main.js中
Vue.http.options.xhr= { withCredentials: true}
使用vue.axios发送请求时配置如下:
axios.defaults.withCredentials= true;jquery请求带上 xhrFields: {withCredentials:true}, crossDomain: true;
$.ajax({
type:"post",
url:"",
xhrFields: {withCredentials:true},
crossDomain: true,
data: {username:$("#username").val()},
dataType:"json",
success:function(data){ }
});
此时问题已解决。
但我查看请求时,还是没有带cookie,太纠结于这一点了。以至于查看全部cookie时突然明白了。
没有带cookie。
浏览器全部cookie
已经有服务器的cookie了。当向服务器发送请求时,会携带cookie,证明是同一会话。
发现火狐的请求头中存在cookie,不知道为什么谷歌的请求头不显示,不明白。望解答。
参考文章:
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie
https://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/
https://blog.csdn.net/czhphp/article/details/65628977
https://blog.csdn.net/liyuling52011/article/details/80013725
https://blog.csdn.net/lililidahaoren/article/details/79566968
https://blog.csdn.net/zhouziyu2011/article/details/61200943
https://blog.csdn.net/onion_ye/article/details/78226237
https://segmentfault.com/q/1010000007643919
https://segmentfault.com/a/1190000009208644?utm_source=tag-newest
https://blog.csdn.net/h1059141989/article/details/83787791
https://segmentfault.com/q/1010000011994975
https://blog.csdn.net/qa60014359/article/details/86511588