Loading

SpringBoot利用Filter来解决跨域问题

1、为什么会出现跨域问题?

浏览器不允许通过ajax请求,来请求另一个网站的资源

 

2、SpringBoot如何通过Filter来解决跨域问题

2.1、写一个 CrosFilter 类来实现 javax.servlet.Filter 接口

public class CrosFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
             throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) servletResponse; //*号表示对所有请求都允许跨域访问 res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }

 

2.2、向Spring容器中添加一个 FilterRegistrationBean 

写一个配置类

@Configuration
public classFilterRegistrationConfig{
 /**
     * 配置跨域访问的过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean registerFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.addUrlPatterns("/*");
        bean.setFilter(new CrosFilter());
        return bean;
    }
}

 

或者写在主启动类中

@SpringBootApplication
public class exampleApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(exampleApplication.class, args);
    }
 
    /**
     * 配置跨域访问的过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean registerFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.addUrlPatterns("/*");
        bean.setFilter(new CrosFilter());
        return bean;
    }
}

 

posted @ 2020-12-17 18:49  青岑  阅读(2002)  评论(0编辑  收藏  举报