Servlet跨域解决(采用Filter方式)

/ Servlet / 2 条评论 / 70浏览

对于前后端分离项目,跨域问题是很常见的问题。

后端解决方案

这里主要介绍Filter方案,Servlet容器都支持,简单粗暴。

Filter方案

定义CorsFilter

public class CorsFilter implements Filter {  

    @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;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type, Authorization");
        filterChain.doFilter(servletRequest, servletResponse);
    }  

    @Override  
    public void destroy() {
    }
}

注册Filter

传统Spring MVC项目

在web.xml中添加:

<filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>xxx.xxx.CorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

这里配置是对于/api/*进行过滤,根据实际情况即可。

Spring Boot项目

方式一(采用注册Bean的方案):

@Bean
public FilterRegistrationBean corsFilter() {
    final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new CorsFilter());
    return registrationBean;
}

方式二(采用@ServletComponentScan的方案):

@ServletComponentScan("xxx.xxx")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

注意需要为CorsFilter添加@WebFilter注解。

不了解Spring Boot如何注册Servlet三大组件的,可以参考Spring Boot之Servlet、Filter、Listener配置

  1. 棒棒哒--------------

    回复
    1. @yoyoig

      造化钟神秀

      回复