springboot 中通過cors協議解決跨域問題

1、對於前後端分離的項目來說,如果前端項目與後端項目部署在兩個不同的域下,那麼勢必會引起跨域問題的出現。

針對跨域問題,我們可能第一個想到的解決方案就是jsonp,並且以前處理跨域問題我基本也是這麼處理。

但是jsonp方式也同樣有不足,不管是對於前端還是後端來說,寫法與我們平常的ajax寫法不同,同樣後端也需要作出相應的更改。並且,jsonp方式只能通過get請求方式來傳遞參數,當然也還有其它的不足之處,針對於此,我並沒有急着使用jsonp的方式來解決跨域問題,去網上找尋其它方式,也就是本文主要所要講的,在springboot中通過cors協議解決跨域問題。

2、Cors協議

H5中的新特性:Cross-Origin Resource Sharing(跨域資源共享)。通過它,我們的開發者(主要指後端開發者)可以決定資源是否能被跨域訪問。

cors是一個w3c標準,它允許瀏覽器(目前ie8以下還不能被支持)像我們不同源的服務器發出xmlHttpRequest請求,我們可以繼續使用ajax進行請求訪問。

具體關於cors協議的文章 ,可以參考http://www.ruanyifeng.com/blog/2016/04/cors.html 這篇文章,講的相當不錯。

3、在springboot中如何通過cors協議解決跨域問題

springmvc4.2版本增加了對cors的支持。

目前我所做的項目基本都是springboot進行開發,所以我這裏貼下在springboot中的使用。

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Value("${hxx.imagePath}")
    private String imagePath;
    @Value("${hxx.uploadPath}")
    private String filePath;

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }


//    @Override
//    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//    	System.out.println("----"+this.getMessageConverters().size());
////        converters.add(responseBodyConverter());
//        //增加controller響應消息json轉換器;在controller直接返回對象可自動轉換爲json
////        converters.add(new MappingJackson2HttpMessageConverter(new ConfigurableObjectMapper()));
//        super.configureMessageConverters(converters);
//        System.out.println("-----"+converters.size());
//    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
        registry.addResourceHandler("/css/**")
                .addResourceLocations("classpath:/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
        registry.addResourceHandler("/editor/**").addResourceLocations("classpath:/editor/");
        registry.addResourceHandler("/ftl/**").addResourceLocations("classpath:/view/");
        registry.addResourceHandler("/images/**").addResourceLocations("file:" + imagePath);
        registry.addResourceHandler("/file/**").addResourceLocations("file:" + imagePath);
        super.addResourceHandlers(registry);
    }

    /*保留國際化*/
    @Bean
    public LocaleChangeInterceptor interceptor() {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("lang");
        return interceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor());
        registry.addInterceptor(new UrlResolveInterceptor());
    }

    @Bean
    public LocaleResolver resolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.US);
        return resolver;
    }
  @Override
    public void addCorsMappings(CorsRegistry registry) {
           registry.addMapping("/api/**")
           .allowedOrigins("http://192.168.1.97")
           .allowedMethods("GET", "POST")
           .allowCredentials(false).maxAge(3600);
    }
}

其父類WebMvcConfigurationSupport 中有方法

/**
	 * Override this method to configure cross origin requests processing.
	 * @since 4.2
	 * @see CorsRegistry
	 */
	protected void addCorsMappings(CorsRegistry registry) {
	}

重寫這個方法就可以實現跨域

用法事例如下

 @Override
    public void addCorsMappings(CorsRegistry registry) {
           registry.addMapping("/api/**")
           .allowedOrigins("http://192.168.1.97")
           .allowedMethods("GET", "POST")
           .allowCredentials(false).maxAge(3600);
    }

學到的老鐵雙擊點贊!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章