配置一个 filter
1 package com.psm.filter; 2 3 import javax.servlet.*; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 import java.io.IOException; 7 8 /** 9 * 添加Ajax Access-Control-Allow-Origin跨域请求 10 * 11 * @author 12 * @create 2018-02-26 17:00 13 **/ 14 public class VisitFilter implements Filter { 15 16 @Override 17 public void init(FilterConfig filterConfig) throws ServletException { 18 19 } 20 21 @Override 22 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 23 HttpServletResponse res = (HttpServletResponse) servletResponse; 24 HttpServletRequest request=(HttpServletRequest)servletRequest; 25 res.setContentType("textml;charset=UTF-8"); 26 res.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); 27 res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 28 res.setHeader("Access-Control-Max-Age", "0"); 29 res.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"); 30 res.setHeader("Access-Control-Allow-Credentials", "true"); 31 res.setHeader("XDomainRequestAllowed","1"); 32 filterChain.doFilter(servletRequest,servletResponse); 33 } 34 35 @Override 36 public void destroy() { 37 38 } 39 }
添加下面这两个
response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));