Springboot處理跨域的實現方式(附Demo)
Springboot處理跨域的方式
1. 基本知識
跨域指的是在一個域下的網頁試圖訪問另一個域下的資源
由于瀏覽器的同源策略,默認情況下,JavaScript 只能在相同的域中進行請求
跨域通常涉及以下概念:
Origin: 包括協議、域名和端口號
比如 http://example.com:80Same-Origin Policy: 瀏覽器的安全策略,限制一個源的文檔或腳本如何能與另一個源的資源進行交互CORS: 允許跨域請求的機制
服務器通過設置特定的響應頭來告知瀏覽器哪些源是允許訪問的
在 Spring Boot 中,處理跨域的方式有幾種,以下是主要的幾種方式:
- 使用 @CrossOrigin 注解: 這種方式較為簡單,適用于控制器層
- 配置全局跨域設置: 這種方式適用于全局配置,可以在 Web 配置類中設置
- 自定義 CorsConfiguration: 適用于更復雜的跨域配置需求,可以在配置類中自定義
以下為Demo示例
2. @CrossOrigin
可以在控制器類或方法上添加 @CrossOrigin 注解
注解的參數可以配置允許的源(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 注解,瀏覽器會阻止跨域請求,因為默認的同源策略不允許不同源之間的請求
3. 全局跨域設置
配置 WebMvcConfigurer 來全局設置跨域
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;
/**
* 配置類,用于全局設置 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 進行自動配置
實現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,配置跨域設置
*
* @return 配置了跨域設置的 FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterBean() {
// 創(chuàng)建 CorsConfiguration 對象
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允許攜帶憑證(如 Cookies)
config.addAllowedOriginPattern("*"); // 允許所有來源的請求(注意:生產環(huán)境中通常不建議使用 *,應具體配置允許的域)
config.addAllowedHeader("*"); // 允許所有請求頭
config.addAllowedMethod("*"); // 允許所有 HTTP 方法(GET, POST, PUT, DELETE 等)
// 創(chuàng)建 UrlBasedCorsConfigurationSource 對象
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config); // 對所有路徑配置跨域設置
// 創(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); // 設置過濾器的順序
return bean;
}
}總結
| 處理方式 | 適用場景 | 配置位置 | 靈活性 | 配置難度 |
|---|---|---|---|---|
| @CrossOrigin 注解 | 單個控制器或方法 | 控制器層 | 低 | 低 |
| 全局配置(WebMvcConfigurer) | 全局設置 | 配置類(WebConfig) | 中 | 中 |
| 自定義 CorsConfiguration | 復雜跨域需求 | 配置類(CustomCorsConfig) | 高 | 高 |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決 Spring RestTemplate post傳遞參數時報錯問題
本文詳解說明了RestTemplate post傳遞參數時報錯的問題及其原由,需要的朋友可以參考下2020-02-02
詳解為什么阿里巴巴禁止使用BigDecimal的equals方法做等值比較
這篇文章主要介紹了詳解為什么阿里巴巴禁止使用BigDecimal的equals方法做等值比較,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09
springboot2+es7使用RestHighLevelClient的示例代碼
本文主要介紹了springboot2+es7使用RestHighLevelClient的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07
Mybatis中一對多(collection)和一對一(association)的組合查詢使用
這篇文章主要介紹了Mybatis中一對多(collection)和一對一(association)的組合查詢使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

