使用Springboot處理跨域的方式
1. 基本知識
跨域指的是在一個域下的網(wǎng)頁試圖訪問另一個域下的資源
由于瀏覽器的同源策略,默認(rèn)情況下,JavaScript 只能在相同的域中進(jìn)行請求
跨域通常涉及以下概念:
Origin
: 包括協(xié)議、域名和端口號
比如 http://example.com:80Same-Origin Policy
: 瀏覽器的安全策略,限制一個源的文檔或腳本如何能與另一個源的資源進(jìn)行交互CORS
: 允許跨域請求的機(jī)制
服務(wù)器通過設(shè)置特定的響應(yīng)頭來告知瀏覽器哪些源是允許訪問的
在 Spring Boot 中,處理跨域的方式有幾種,以下是主要的幾種方式:
- 使用 @CrossOrigin 注解: 這種方式較為簡單,適用于控制器層
- 配置全局跨域設(shè)置: 這種方式適用于全局配置,可以在 Web 配置類中設(shè)置
- 自定義 CorsConfiguration: 適用于更復(fù)雜的跨域配置需求,可以在配置類中自定義
以下為Demo示例
2. @CrossOrigin
可以在控制器類或方法上添加 @CrossOrigin 注解
注解的參數(shù)可以配置允許的源(origins)、允許的請求方法(methods)、允許的請求頭(allowedHeaders)、是否允許憑證(allowCredentials)等
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class MyController { @CrossOrigin(origins = "http://example.com") @GetMapping("/data") public String getData() { return "Data from server"; } }
如果不使用 @CrossOrigin 注解,瀏覽器會阻止跨域請求,因為默認(rèn)的同源策略不允許不同源之間的請求
3. 全局跨域設(shè)置
配置 WebMvcConfigurer 來全局設(shè)置跨域
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置類,用于全局設(shè)置 CORS(跨域資源共享)配置 */ @Configuration public class WebConfig implements WebMvcConfigurer { /** * 配置跨域請求的映射規(guī)則 * * @param registry 用于注冊 CORS 配置的注冊表 */ @Override public void addCorsMappings(CorsRegistry registry) { // 添加跨域映射規(guī)則 registry.addMapping("/**") // 允許所有路徑的跨域請求 .allowedOrigins("http://example.com") // 允許來自 http://example.com 的跨域請求 .allowedMethods("GET", "POST", "PUT", "DELETE") // 允許的請求方法 .allowedHeaders("*") // 允許所有請求頭 .allowCredentials(true); // 允許攜帶憑證(如 Cookies) } }
4. 自定義 CorsConfiguration
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CustomCorsConfig implements WebMvcConfigurer { @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://example.com")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); configuration.setAllowedHeaders(Arrays.asList("*")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
5. 實戰(zhàn)
以下展示項目中的跨域
用 @AutoConfiguration 進(jìn)行自動配置
實現(xiàn)WebMvcConfigurer 接口,并通過 FilterRegistrationBean 注冊自定義的跨域過濾器 CorsFilter 和其他過濾器
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @Configuration @AutoConfiguration @EnableConfigurationProperties(WebProperties.class) public class WebAutoConfiguration implements WebMvcConfigurer { /** * 創(chuàng)建一個 CorsFilter 過濾器的 Bean,配置跨域設(shè)置 * * @return 配置了跨域設(shè)置的 FilterRegistrationBean */ @Bean public FilterRegistrationBean<CorsFilter> corsFilterBean() { // 創(chuàng)建 CorsConfiguration 對象 CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 允許攜帶憑證(如 Cookies) config.addAllowedOriginPattern("*"); // 允許所有來源的請求(注意:生產(chǎn)環(huán)境中通常不建議使用 *,應(yīng)具體配置允許的域) config.addAllowedHeader("*"); // 允許所有請求頭 config.addAllowedMethod("*"); // 允許所有 HTTP 方法(GET, POST, PUT, DELETE 等) // 創(chuàng)建 UrlBasedCorsConfigurationSource 對象 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); // 對所有路徑配置跨域設(shè)置 // 創(chuàng)建并返回一個 FilterRegistrationBean 實例,注冊 CorsFilter return createFilterBean(new CorsFilter(source), Integer.MIN_VALUE); } /** * 創(chuàng)建 DemoFilter Bean,演示模式 * * @return 配置了 DemoFilter 的 FilterRegistrationBean */ @Bean @ConditionalOnProperty(value = "demo", havingValue = "true") public FilterRegistrationBean<DemoFilter> demoFilter() { // 創(chuàng)建并返回一個 FilterRegistrationBean 實例,注冊 DemoFilter return createFilterBean(new DemoFilter(), Integer.MIN_VALUE); } /** * 創(chuàng)建 FilterRegistrationBean 實例的通用方法 * * @param filter 需要注冊的過濾器實例 * @param order 過濾器的執(zhí)行順序 * @return 配置了過濾器的 FilterRegistrationBean 實例 */ public static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, Integer order) { FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter); bean.setOrder(order); // 設(shè)置過濾器的順序 return bean; } }
總結(jié)
處理方式 | 適用場景 | 配置位置 | 靈活性 | 配置難度 |
---|---|---|---|---|
@CrossOrigin 注解 | 單個控制器或方法 | 控制器層 | 低 | 低 |
全局配置(WebMvcConfigurer) | 全局設(shè)置 | 配置類(WebConfig) | 中 | 中 |
自定義 CorsConfiguration | 復(fù)雜跨域需求 | 配置類(CustomCorsConfig) | 高 | 高 |
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java Swing組件復(fù)選框JCheckBox用法示例
這篇文章主要介紹了Java Swing組件復(fù)選框JCheckBox用法,結(jié)合具體實例形式分析了Swing復(fù)選框JCheckBox簡單用法與相關(guān)操作注意事項,需要的朋友可以參考下2017-11-11java Hibernate 一對多自身關(guān)聯(lián)問題
formBean在提交表單的時候,域中數(shù)據(jù)庫在下一次中仍然保留引起的,struts formBean 默認(rèn)的scope為session,手動設(shè)置為request,就好了2008-07-07Java在Excel中創(chuàng)建多級分組、折疊或展開分組的實現(xiàn)
這篇文章主要介紹了Java在Excel中創(chuàng)建多級分組、折疊或展開分組的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05Java Swing實現(xiàn)坦克大戰(zhàn)游戲
這篇文章主要介紹了Java Swing實現(xiàn)坦克大戰(zhàn)游戲,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有很大的幫助喲,需要的朋友可以參考下2021-05-05IDEA中WebService生成Java代碼并調(diào)用外部接口實現(xiàn)代碼
這篇文章主要介紹了IDEA中WebService生成Java代碼并調(diào)用外部接口實現(xiàn),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05