Spring MVC 解決CORS跨域問題

4.2之後,Spring Framework可以解決跨域問題,開箱即用,下面是從官方文檔總結了3種解決辦法。

  • 利用@CrossOrigin註解,作用在Controller的方法上,可以指定originsallowedHeadersexposedHeadersallowCredentialsmaxAge屬性。優點是可以指定某個或者某些接口跨域訪問,缺點則是若需要全局支持跨域訪問,則每個接口都需要加註解。示例如下:
@CrossOrigin(origins = {"http://spring-framework.yjy.com"}, maxAge = 3600)
@RequestMapping(value = "/api1")
public ModelAndView api1() {
    return generateOkResponse();
}
  • 在MVC配置文件配置mvc:cors標籤:支持多個mvc:mapping標籤,通過mvc:mapping標籤的path屬性可以指定需要支持跨域訪問的路徑,這樣既可以單獨指定也可以全局指定。示例如下:
<mvc:cors>
    <mvc:mapping path="/cors/api2"
                 allowed-origins="http://spring-framework.yjy.com"
                 allowed-methods="GET,POST,PUT,POST"
                 max-age="3600" />
</mvc:cors>
  • Filter級的攔截:繼承CorsFilter,注入自定義的CorsConfigurationSource,CorsConfigurationSource有一個Map類型的corsConfigurations成員變量,用來維護path(跨域訪問路徑)和CorsConfiguration(跨域訪問配置)的關係。示例如下:
public class MyCorsFilter extends CorsFilter {

    public MyCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://spring-framework.yjy.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/cors/api3", config);

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