使用filter解决跨域

在web.xml配置拦截器

	<filter>
		<filter-name>servletFilterTest</filter-name>
		<filter-class>cn.test.intercepter.ServletFilterTest</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>servletFilterTest</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

过滤器代码:

import org.springframework.web.bind.annotation.RequestMethod;

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

public class ServletFilterTest implements Filter {


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

    }

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

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        httpServletRequest.getSession();
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Content-type", "application/json");
        httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");

        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return ;
        }
        filterChain.doFilter(httpServletRequest, httpResponse);

    }

    @Override
    public void destroy() {

    }
}
posted @ 2019-05-27 13:49  你就像甜甜的益达  阅读(132)  评论(0编辑  收藏  举报