欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot處理跨域的實現(xiàn)方式(附Demo)

 更新時間:2025年04月01日 11:54:39   作者:碼農(nóng)研究僧  
這篇文章主要介紹了Springboot處理跨域的實現(xiàn)方式(附Demo),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

Springboot處理跨域的方式

1. 基本知識

跨域指的是在一個域下的網(wǎng)頁試圖訪問另一個域下的資源

由于瀏覽器的同源策略,默認(rèn)情況下,JavaScript 只能在相同的域中進行請求

跨域通常涉及以下概念:

  • Origin: 包括協(xié)議、域名和端口號
    比如 http://example.com:80
  • Same-Origin Policy: 瀏覽器的安全策略,限制一個源的文檔或腳本如何能與另一個源的資源進行交互
  • CORS: 允許跨域請求的機制
    服務(wù)器通過設(shè)置特定的響應(yīng)頭來告知瀏覽器哪些源是允許訪問的

在 Spring Boot 中,處理跨域的方式有幾種,以下是主要的幾種方式:

  1. 使用 @CrossOrigin 注解: 這種方式較為簡單,適用于控制器層
  2. 配置全局跨域設(shè)置: 這種方式適用于全局配置,可以在 Web 配置類中設(shè)置
  3. 自定義 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 進行自動配置

實現(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)文章

  • 解決PageHelper的上下文問題導(dǎo)致SQL查詢結(jié)果不正確

    解決PageHelper的上下文問題導(dǎo)致SQL查詢結(jié)果不正確

    主要介紹了PageHelper在使用過程中出現(xiàn)的分頁上下文問題,并分析了可能的原因和解決方案,主要解決方案包括每次分頁查詢后調(diào)用`PageHelper.clearPage()`清理分頁上下文,確保每次查詢前正確調(diào)用`startPage`,以及避免在條件判斷未執(zhí)行SQL時影響后續(xù)查詢
    2024-12-12
  • JAVA中方法的聲明及使用方式(繼承、多態(tài)、封裝)

    JAVA中方法的聲明及使用方式(繼承、多態(tài)、封裝)

    這篇文章主要介紹了JAVA中方法的聲明及使用方式(繼承、多態(tài)、封裝),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • java網(wǎng)上圖書商城(4)購物車模塊1

    java網(wǎng)上圖書商城(4)購物車模塊1

    這篇文章主要為大家詳細(xì)介紹了java網(wǎng)上圖書商城,購物車模塊,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-12-12
  • SpringBoot使用JPA實現(xiàn)查詢部分字段

    SpringBoot使用JPA實現(xiàn)查詢部分字段

    這篇文章主要介紹了SpringBoot使用JPA實現(xiàn)查詢部分字段方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • java實現(xiàn)文件上傳功能

    java實現(xiàn)文件上傳功能

    這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)文件上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-12-12
  • 關(guān)于IDEA中spring-cloud-starter-alibaba-nacos-discovery 無法引入問題

    關(guān)于IDEA中spring-cloud-starter-alibaba-nacos-discovery 無法引入問題

    這篇文章主要介紹了關(guān)于IDEA中spring-cloud-starter-alibaba-nacos-discovery 無法引入問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-02-02
  • Java軟件生產(chǎn)監(jiān)控工具Btrace使用方法詳解

    Java軟件生產(chǎn)監(jiān)控工具Btrace使用方法詳解

    這篇文章主要介紹了Java軟件生產(chǎn)監(jiān)控工具Btrace使用方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • springboot在filter中如何用threadlocal存放用戶身份信息

    springboot在filter中如何用threadlocal存放用戶身份信息

    這篇文章主要介紹了springboot中在filter中如何用threadlocal存放用戶身份信息,本文章主要描述通過springboot的filter類,在過濾器中設(shè)置jwt信息進行身份信息保存的方法,需要的朋友可以參考下
    2024-07-07
  • 入門Java線程基礎(chǔ)一篇就夠了

    入門Java線程基礎(chǔ)一篇就夠了

    線程是進程中的一個實體,是被系統(tǒng)獨立調(diào)度和分派的基本單位,線程自己不擁有系統(tǒng)資源,只擁有一點在運行中必不可少的資源,但它可與同屬一個進程的其它線程共享進程所擁有的全部資源
    2021-06-06
  • Spring Boot 與 Kotlin 上傳文件的示例代碼

    Spring Boot 與 Kotlin 上傳文件的示例代碼

    這篇文章主要介紹了Spring Boot 與 Kotlin 上傳文件的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01

最新評論