1. 程式人生 > 實用技巧 >SpringBoot利用Filter來解決跨域問題

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;
    }
}