1. 程式人生 > >Spring MVC 解決CORS跨域問題

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