在Spring MVC中處理跨域問題可以通過以下幾種方式實現,確保前后端能夠正常通信:
方法一:使用 @CrossOrigin
注解
適用于局部控制跨域配置,直接在Controller或方法上添加注解。
示例代碼:
@RestController
@CrossOrigin(origins = "http://localhost:8080") // 允許指定源
public class MyController {@GetMapping("/data")public String getData() {return "Hello, CORS!";}
}
- 參數說明:
origins
: 允許的源(多個用逗號分隔,或用@CrossOrigin(origins = "*")
允許所有,但不推薦生產環境)。methods
: 允許的HTTP方法(如RequestMethod.GET
)。allowedHeaders
: 允許的請求頭。allowCredentials
: 是否允許發送Cookie(需與前端配置一致)。
方法二:全局配置 WebMvcConfigurer
適用于全局跨域設置,統一管理所有接口的跨域規則。
步驟:
- 創建配置類實現
WebMvcConfigurer
。 - 重寫
addCorsMappings
方法。
示例代碼:
@Configuration
public class CorsGlobalConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") // 匹配所有路徑.allowedOrigins("http://localhost:8080", "https://example.com").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*").allowCredentials(true).maxAge(3600); // 預檢請求緩存時間(秒)}
}
方法三:使用 CorsFilter
通過自定義過濾器精細化控制跨域行為,適合復雜場景。
示例代碼:
@Configuration
public class CorsFilterConfig {@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration config = new CorsConfiguration();config.setAllowCredentials(true);config.addAllowedOrigin("http://localhost:8080");config.addAllowedHeader("*");config.addAllowedMethod("*");source.registerCorsConfiguration("/**", config); // 對所有路徑生效return new CorsFilter(source);}
}
方法四:結合 Spring Security
若項目集成了Spring Security,需額外配置安全規則以啟用CORS。
步驟:
- 在安全配置類中啟用CORS。
- 定義
CorsConfigurationSource
Bean。
示例代碼:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.cors().and() // 啟用CORS.csrf().disable().authorizeRequests().anyRequest().authenticated();}@Beanpublic CorsConfigurationSource corsConfigurationSource() {CorsConfiguration config = new CorsConfiguration();config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));config.setAllowedHeaders(Arrays.asList("*"));config.setAllowCredentials(true);UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);return source;}
}
方法五:通過 <mvc:cors>
命名空間配置全局跨域規則
在 Spring MVC 中,如果項目使用 applicationContext.xml
進行配置(基于 XML 的配置方式),這是最直接的 XML 配置方式,適用于全局跨域設置。
步驟:
-
確保 XML 文件頭部聲明了
mvc
命名空間:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd">
-
在
<mvc:annotation-driven>
標簽內配置跨域規則:<mvc:annotation-driven><mvc:cors><!-- 配置全局跨域 --><mvc:mapping path="/**"allowed-origins="http://localhost:8080, https://example.com"allowed-methods="GET, POST, PUT, DELETE, OPTIONS"allowed-headers="Content-Type, Authorization"allow-credentials="true"max-age="3600"/></mvc:cors> </mvc:annotation-driven>
- 參數說明:
path
: 匹配的 URL 路徑模式(支持 Ant 風格,如/api/**
)。allowed-origins
: 允許的源(多個用逗號分隔)。allowed-methods
: 允許的 HTTP 方法。allowed-headers
: 允許的請求頭。allow-credentials
: 是否允許發送 Cookie(對應allowCredentials(true)
)。max-age
: 預檢請求緩存時間(秒)。
- 參數說明:
方法六:通過自定義 CorsFilter
Bean 配置
通過applicationContext.xml配置處理跨域問題時,如果需要對跨域行為進行更細粒度的控制(例如動態配置),可以手動注冊 CorsFilter
。
步驟:
-
在
applicationContext.xml
中定義CorsFilter
Bean:<bean id="corsFilter" class="org.springframework.web.filter.CorsFilter"><constructor-arg><bean class="org.springframework.web.cors.UrlBasedCorsConfigurationSource"><property name="corsConfigurations"><map><entry key="/**"><bean class="org.springframework.web.cors.CorsConfiguration"><property name="allowedOrigins"><list><value>http://localhost:8080</value><value>https://example.com</value></list></property><property name="allowedMethods"><list><value>GET</value><value>POST</value><value>PUT</value><value>DELETE</value><value>OPTIONS</value></list></property><property name="allowedHeaders"><list><value>Content-Type</value><value>Authorization</value></list></property><property name="allowCredentials" value="true"/><property name="maxAge" value="3600"/></bean></entry></map></property></bean></constructor-arg> </bean>
-
確保
CorsFilter
優先執行:
在web.xml
中,將CorsFilter
注冊為第一個 Filter:<filter><filter-name>corsFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping><filter-name>corsFilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping>
完整示例:結合 applicationContext.xml
和 web.xml
applicationContext.xml
配置:
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 啟用注解驅動并配置 CORS --><mvc:annotation-driven><mvc:cors><mvc:mapping path="/**"allowed-origins="http://localhost:8080"allowed-methods="GET, POST, PUT, DELETE"allowed-headers="Content-Type, Authorization"allow-credentials="true"max-age="3600"/></mvc:cors></mvc:annotation-driven></beans>
web.xml
配置(確保 Filter 順序):
<filter><filter-name>corsFilter</filter-name><filter-class>org.springframework.web.filter.CorsFilter</filter-class>
</filter>
<filter-mapping><filter-name>corsFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>
通過方式五和方式六,可以在基于 XML 的 Spring MVC 項目中靈活配置跨域規則。推薦使用 <mvc:cors>
命名空間配置,簡單且直接;若需動態控制,則選擇 CorsFilter
。
關鍵注意事項
- 預檢請求(Preflight):瀏覽器會先發送
OPTIONS
請求檢查服務器是否允許跨域。確保配置中包含allowedMethods
并正確處理OPTIONS
。 - 攜帶憑證(Cookies):若需傳輸Cookies,前端需設置
withCredentials: true
,后端需設置allowCredentials(true)
,且allowedOrigins
不能為*
。 - 生產環境安全:避免使用通配符
*
,應明確指定允許的源、方法和頭信息。 allowedOrigins
vsallowedOriginPatterns
:- 如果使用 Spring 5.3+,可以用
allowedOriginPatterns
支持通配符模式(如http://*.example.com
)。 - XML 配置中需通過
<list>
手動指定具體域名。
- 如果使用 Spring 5.3+,可以用
- 與 Spring Security 集成:
- 如果項目集成了 Spring Security,需在安全配置中啟用 CORS:
<http auto-config="true" use-expressions="true"><cors/> <!-- 啟用 CORS --><!-- 其他安全配置 --> </http>
- 如果項目集成了 Spring Security,需在安全配置中啟用 CORS:
通過上述方法,可靈活解決Spring MVC中的跨域問題,根據項目需求選擇最合適的方案。