帶cookie的跨域2
1谭胚、Access-Control-Allow-Origin:具體URL
(1)Access-Control-Allow-Origin設(shè)置具體的URL荣回,只能解決設(shè)置的具體URL跨域問題兜喻,不解決帶Cookie的所有URL跨域請(qǐng)求
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請(qǐng)求唯沮,origin必須全匹配
//???????res.addHeader("Access-Control-Allow-Origin",origin);
???????res.addHeader("Access-Control-Allow-Origin","http://localhost:8082");
//???????res.addHeader("Access-Control-Allow-Methods","GET");
??????? // *號(hào)表示支持所有的域名(除了帶cookie請(qǐng)求外)
//???????res.addHeader("Access-Control-Allow-Origin","*");
??????? // *號(hào)表示支持所有的請(qǐng)求方法
???????res.addHeader("Access-Control-Allow-Methods","*");
???????res.addHeader("Access-Control-Allow-Headers","Content-Type");
??????? //設(shè)置OPTIONS預(yù)檢命令緩存
???????res.addHeader("Access-Control-Max-Age", "60000");
??????? //允許帶cookie請(qǐng)求跨域
??????? res.addHeader("Access-Control-Allow-Credentials","true");
??????? filterChain.doFilter(servletRequest,servletResponse);
??? }
(2)只有http://localhost:8082訪問才能跨域救鲤,如果是http://127.0.0.1:8082訪問咆蒿,就不滿足跨域
2东抹、修改后臺(tái)代碼,獲取請(qǐng)求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請(qǐng)求沃测,origin必須全匹配
???????res.addHeader("Access-Control-Allow-Origin",origin);
//???????res.addHeader("Access-Control-Allow-Origin","http://localhost:8082");
//???????res.addHeader("Access-Control-Allow-Methods","GET");
???????// *號(hào)表示支持所有的域名(除了帶cookie請(qǐng)求外)
//???????res.addHeader("Access-Control-Allow-Origin","*");
???????// *號(hào)表示支持所有的請(qǐng)求方法
???????res.addHeader("Access-Control-Allow-Methods","*");
???? ???res.addHeader("Access-Control-Allow-Headers","Content-Type");
???????//設(shè)置OPTIONS預(yù)檢命令緩存
???????res.addHeader("Access-Control-Max-Age", "60000");
???????//允許帶cookie請(qǐng)求跨域
???????res.addHeader("Access-Control-Allow-Credentials","true");
???????filterChain.doFilter(servletRequest, servletResponse);
}
http://localhost:8082訪問能跨域缭黔,http://127.0.0.1:8082訪問也能跨域