带cookie的跨域2
1、Access-Control-Allow-Origin:具体URL
(1)Access-Control-Allow-Origin设置具体的URL,只能解决设置的具体URL跨域问题,不解决带Cookie的所有URL跨域请求
CrossFilter代码:
@Override
public void doFilter(ServletRequestservletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {
HttpServletResponse res =(HttpServletResponse) servletResponse;
HttpServletRequest req =(HttpServletRequest) servletRequest;
String origin =req.getHeader("Origin");
//带cookie请求,origin必须全匹配
// res.addHeader("Access-Control-Allow-Origin",origin);
res.addHeader("Access-Control-Allow-Origin","http://localhost:8082");
// res.addHeader("Access-Control-Allow-Methods","GET");
// *号表示支持所有的域名(除了带cookie请求外)
// res.addHeader("Access-Control-Allow-Origin","*");
// *号表示支持所有的请求方法
res.addHeader("Access-Control-Allow-Methods","*");
res.addHeader("Access-Control-Allow-Headers","Content-Type");
//设置OPTIONS预检命令缓存
res.addHeader("Access-Control-Max-Age", "60000");
//允许带cookie请求跨域
res.addHeader("Access-Control-Allow-Credentials","true");
filterChain.doFilter(servletRequest,servletResponse);
}
(2)只有http://localhost:8082访问才能跨域,如果是http://127.0.0.1:8082访问,就不满足跨域
2、修改后台代码,获取请求Header中Origin
CrossFilter代码:
@Override
public void doFilter(ServletRequest servletRequest, ServletResponseservletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletResponse res = (HttpServletResponse) servletResponse;
HttpServletRequest req = (HttpServletRequest) servletRequest;
Stringorigin = req.getHeader("Origin");
//带cookie请求,origin必须全匹配
res.addHeader("Access-Control-Allow-Origin",origin);
// res.addHeader("Access-Control-Allow-Origin","http://localhost:8082");
// res.addHeader("Access-Control-Allow-Methods","GET");
// *号表示支持所有的域名(除了带cookie请求外)
// res.addHeader("Access-Control-Allow-Origin","*");
// *号表示支持所有的请求方法
res.addHeader("Access-Control-Allow-Methods","*");
res.addHeader("Access-Control-Allow-Headers","Content-Type");
//设置OPTIONS预检命令缓存
res.addHeader("Access-Control-Max-Age", "60000");
//允许带cookie请求跨域
res.addHeader("Access-Control-Allow-Credentials","true");
filterChain.doFilter(servletRequest, servletResponse);
}
http://localhost:8082访问能跨域,http://127.0.0.1:8082访问也能跨域