SpringMVC中filter实现跨域请求

1.需求背景

   如果在项目中有需要暴露某一接口给外部服务调用,那么对于web项目势必会出现跨域情况,那么如何解决这个跨域呢?

2.实现方案

i. CORSFilter

public class CORSFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //域名列表
        String domains = "A,B,C";

        try {
            String originHeads = request.getHeader("Origin");
            LoggerUtil.info(logger, "[CORSFilter] domain=", originHeads, ",diamond domains=", domains);
            String[] corsList = domains.split(",");
            for (String domain : corsList) {
                if (!domain.equals(originHeads)) {
                    continue;
                }

                response.setHeader("Access-Control-Allow-Origin", domain);
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "0");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X-XSRF-TOKEN");
            }

        } catch (Exception ex) {
            LoggerUtil.error(logger, ex, "[CORSFilter] domains split err=");
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

  
}

注意每次请求只能允许一个域名,所以这里得遍历设置可允许的域名

ii 在web.xml注册CORSFilter

 
    
        CORSFilter
        com.xxx.config.CORSFilter
    
    
        CORSFilter
        /cors/*
    

配置需要实现跨域的接口URL通配

你可能感兴趣的:(springmvc)