最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

Springboot處理跨域的方式

1. 基本知識

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

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

跨域通常涉及以下概念:

  • Origin: 包括協(xié)議、域名和端口號
    比如 http://example.com:80
  • Same-Origin Policy: 瀏覽器的安全策略,限制一個源的文檔或腳本如何能與另一個源的資源進(jìn)行交互
  • 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 進(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)文章

  • 關(guān)于Java三大特性之多態(tài)的總結(jié)

    關(guān)于Java三大特性之多態(tài)的總結(jié)

    這篇文章主要介紹了關(guān)于Java三大特性之多態(tài)的總結(jié),內(nèi)容詳細(xì),涉及多態(tài)的定義,存在條件,好處,分類及實現(xiàn)方式等相關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • java中的快捷鍵小結(jié)

    java中的快捷鍵小結(jié)

    以下是myeclipse中的所有快捷鍵列表
    2013-03-03
  • Java的枚舉,注解和反射(二)

    Java的枚舉,注解和反射(二)

    今天小編就為大家分享一篇關(guān)于Java枚舉,注解與反射原理說明,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2021-07-07
  • Java8 Optional原理及用法解析

    Java8 Optional原理及用法解析

    這篇文章主要介紹了Java8 Optional原理及用法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-09-09
  • Java實現(xiàn)順序表的操作

    Java實現(xiàn)順序表的操作

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)順序表的基本操作,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • Kotlin與Java 泛型缺陷和應(yīng)用場景詳解

    Kotlin與Java 泛型缺陷和應(yīng)用場景詳解

    這篇文章主要為大家介紹了Kotlin與Java 泛型缺陷和應(yīng)用場景詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12
  • JDBC 程序的常見錯誤及調(diào)試方法

    JDBC 程序的常見錯誤及調(diào)試方法

    本文是《Java Web開發(fā)教程——入門與提高篇(JSP+Servlet)》一書《第9章 JDBC技術(shù)》的補充內(nèi)容。
    2009-06-06
  • IntelliJ IDEA連接MySQL數(shù)據(jù)庫詳細(xì)圖解

    IntelliJ IDEA連接MySQL數(shù)據(jù)庫詳細(xì)圖解

    今天小編就為大家分享一篇關(guān)于intellij idea連接mysql數(shù)據(jù)庫詳細(xì)圖解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • Java發(fā)送SNMP至交換機獲取交換機狀態(tài)實現(xiàn)方式

    Java發(fā)送SNMP至交換機獲取交換機狀態(tài)實現(xiàn)方式

    文章介紹使用SNMP4J庫(2.7.0)通過RCF1213-MIB協(xié)議獲取交換機單/多路狀態(tài),需開啟SNMP支持,重點對比SNMPv1、v2c、v3的安全性差異,并說明通過PDU封裝請求及GETBULK操作提升數(shù)據(jù)獲取效率
    2025-09-09
  • springboot項目配置ssl連接的實現(xiàn)示例

    springboot項目配置ssl連接的實現(xiàn)示例

    本文主要介紹了springboot項目配置ssl連接的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-05-05

最新評論

嘉祥县| 孝感市| 铁岭县| 太保市| 威宁| 安溪县| 石棉县| 格尔木市| 鹤峰县| 宁武县| 精河县| 兰西县| 门头沟区| 忻州市| 固原市| 兴山县| 万宁市| 武威市| 柯坪县| 甘肃省| 疏附县| 鄂州市| 屯门区| 都兰县| 渝北区| 东阿县| 常山县| 马山县| 龙口市| 南木林县| 于田县| 福清市| 沅陵县| 宜丰县| 宝兴县| 工布江达县| 滨海县| 阿合奇县| 甘洛县| 沁水县| 德庆县|