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

使用Springboot處理跨域的方式

 更新時間:2024年09月05日 08:39:33   作者:碼農(nóng)研究僧  
這篇文章主要介紹了使用Springboot處理跨域的方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

1. 基本知識

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

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

跨域通常涉及以下概念:

  • Origin: 包括協(xié)議、域名和端口號
    比如 http://example.com:80
  • Same-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 使用異常的好處總結(jié)

    java 使用異常的好處總結(jié)

    這篇文章主要介紹了java 使用異常的好處總結(jié)的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • Java Swing組件復(fù)選框JCheckBox用法示例

    Java Swing組件復(fù)選框JCheckBox用法示例

    這篇文章主要介紹了Java Swing組件復(fù)選框JCheckBox用法,結(jié)合具體實例形式分析了Swing復(fù)選框JCheckBox簡單用法與相關(guān)操作注意事項,需要的朋友可以參考下
    2017-11-11
  • java Hibernate 一對多自身關(guān)聯(lián)問題

    java Hibernate 一對多自身關(guān)聯(lián)問題

    formBean在提交表單的時候,域中數(shù)據(jù)庫在下一次中仍然保留引起的,struts formBean 默認(rèn)的scope為session,手動設(shè)置為request,就好了
    2008-07-07
  • Java在Excel中創(chuàng)建多級分組、折疊或展開分組的實現(xiàn)

    Java在Excel中創(chuàng)建多級分組、折疊或展開分組的實現(xiàn)

    這篇文章主要介紹了Java在Excel中創(chuàng)建多級分組、折疊或展開分組的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • MyBatis傳遞多個參數(shù)方式

    MyBatis傳遞多個參數(shù)方式

    這篇文章主要介紹了MyBatis傳遞多個參數(shù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Java Swing實現(xiàn)坦克大戰(zhàn)游戲

    Java Swing實現(xiàn)坦克大戰(zhàn)游戲

    這篇文章主要介紹了Java Swing實現(xiàn)坦克大戰(zhàn)游戲,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有很大的幫助喲,需要的朋友可以參考下
    2021-05-05
  • MyBatis-Flex實現(xiàn)分頁查詢的示例代碼

    MyBatis-Flex實現(xiàn)分頁查詢的示例代碼

    在MyBatis-Flex中實現(xiàn)分頁查詢時,需要注意維護(hù)一個獲取數(shù)據(jù)庫總數(shù)的方法,詳細(xì)介紹了UserService、UserServiceImpl類以及Mapper.xml配置,感興趣的可以了解一下
    2024-10-10
  • 深入淺析Java注解框架

    深入淺析Java注解框架

    這篇文章主要介紹了深入淺析Java注解框架的相關(guān)資料,介紹的非常詳細(xì),具有參考價值,需要的朋友參考下吧
    2016-05-05
  • Java中的Kafka為什么性能這么快及4大核心詳析

    Java中的Kafka為什么性能這么快及4大核心詳析

    這篇文章主要介紹了Java中的Kafka為什么性能這么快及4大核心詳析,文章通過圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09
  • IDEA中WebService生成Java代碼并調(diào)用外部接口實現(xiàn)代碼

    IDEA中WebService生成Java代碼并調(diào)用外部接口實現(xiàn)代碼

    這篇文章主要介紹了IDEA中WebService生成Java代碼并調(diào)用外部接口實現(xiàn),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-05-05

最新評論