解决cors跨域的filter

Posted grey-wolf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决cors跨域的filter相关的知识,希望对你有一定的参考价值。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * desc:
 *
 * @author: 
 * creat_date: 2018/1/4
 * creat_time: 17:33
 **/
@Order(Ordered.LOWEST_PRECEDENCE - 1)
@WebFilter(filterName = "headersCORSFilter", urlPatterns = "/*")
public class HeadersCorsFilter implements Filter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(HeadersCorsFilter.class);

    private int order = Ordered.LOWEST_PRECEDENCE - 1;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResp = (HttpServletResponse) response;
        httpResp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
        httpResp.setHeader("Access-Control-Allow-Origin", "*");
        httpResp.setHeader("Access-Control-Allow-Credentials", "true");
        httpResp.setHeader("Access-Control-Max-Age", "3600");
        httpResp.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin," +
                "Access-Control-Request-Method,Access-Control-Request-Headers,userID,Authentication,authentication,content-type");

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public int getOrder() {
        return order;
    }
}

 

以上是关于解决cors跨域的filter的主要内容,如果未能解决你的问题,请参考以下文章

如何用CORS来解决JS中跨域的问题

11-6 CORS跨域资源共享解决

11-6 CORS跨域资源共享解决

Spring MVC学习(11)—跨域的介绍以及使用CORS解决跨域问题

解决ajax跨域的办法,代理,cors,jsonp

tomcat跨域的若干实现总结