Java跨域

使用Filter处理跨域

  1. 创建Filter
public class CorsFilter implements Filter {
    private String allowedOrigins = "*";
    private String allowedMethods = "GET, POST";
    private String allowedHeaders = "*";
    private String exposedHeaders = "";
    private String allowCredentials = "false";
    private String maxAge = "1800";


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (filterConfig.getInitParameter("allowedOrigins") != null) {
            allowedOrigins = filterConfig.getInitParameter("allowedOrigins");
        }

        if (filterConfig.getInitParameter("allowedMethods") != null) {
            allowedMethods = filterConfig.getInitParameter("allowedMethods");
        }

        if (filterConfig.getInitParameter("allowedHeaders") != null) {
            allowedHeaders = filterConfig.getInitParameter("allowedHeaders");
        }

        if (filterConfig.getInitParameter("exposedHeaders") != null) {
            exposedHeaders = filterConfig.getInitParameter("exposedHeaders");
        }

        if (filterConfig.getInitParameter("allowCredentials") != null) {
            allowCredentials = filterConfig.getInitParameter("allowCredentials");
        }

        if (filterConfig.getInitParameter("maxAge") != null) {
            maxAge = filterConfig.getInitParameter("maxAge");
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setHeader("Access-Control-Allow-Origin", this.allowedOrigins);
        response.setHeader("Access-Control-Allow-Methods", this.allowedMethods);
        response.setHeader("Access-Control-Allow-Headers", this.allowedHeaders);

        if (this.allowCredentials != null) {
            response.setHeader("Access-Control-Allow-Credentials", this.allowCredentials);
        }

        if (this.exposedHeaders != null) {
            response.setHeader("Access-Control-Expose-Headers", this.exposedHeaders);
        }

        if (this.maxAge != null) {
            response.setHeader("Access-Control-Max-Age", maxAge);
        }

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        if (!httpServletRequest.getMethod().equals("OPTIONS")) {
            filterChain.doFilter(servletRequest, response);
        }
    }

    @Override
    public void destroy() {

    }
}
  1. 配置Web.xml

注意 Filter 的顺序,请求应该最先到达这个Filter

  
    corsFilter
    com.chuchujie.mall.gold.common.web.CorsFilter
    
      allowedMethods
      GET, POST, OPTIONS
    
    
    
      allowedHeaders
      token
    
  

  
    corsFilter
    /api/*
  

你可能感兴趣的:(Java跨域)