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

springboot項目實現(xiàn)配置跨域

 更新時間:2024年09月05日 08:59:05   作者:wangpeng1201  
這篇文章主要介紹了springboot項目實現(xiàn)配置跨域問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

在Spring Boot項目中配置跨域(CORS,Cross-Origin Resource Sharing)主要是為了允許來自不同源(不同的協(xié)議、域名或端口)的前端應(yīng)用能夠訪問后端API。

Spring Boot提供了多種方式來配置跨域支持。

1. 使用@CrossOrigin注解

最簡單的方式是在控制器或者具體的方法上使用@CrossOrigin注解。

例如:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "http://example.com") // 允許來自 http://example.com 的跨域請求
public class MyController {

    @GetMapping("/myEndpoint")
    public String myMethod() {
        return "Hello, World!";
    }
}

這將允許來自http://example.com的跨域請求訪問/myEndpoint這個接口。

2. 全局跨域配置

如果你想要為整個應(yīng)用配置跨域支持,可以在配置類中添加一個WebMvcConfigurer的實現(xiàn):

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 WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 為所有請求添加跨域支持
                .allowedOrigins("*")    // 允許任何源
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允許的HTTP方法
                .allowCredentials(true); // 是否允許發(fā)送Cookie信息
    }
}

這個配置將允許任何源的跨域請求,并且允許GET、POSTPUTDELETE方法。

allowCredentials設(shè)置為true表示允許客戶端發(fā)送Cookie信息。

3. 使用CorsFilter

如果需要更細(xì)致的控制,可以創(chuàng)建一個CorsFilter并注冊為Bean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins("*");
        configuration.setAllowedMethods("GET", "POST", "PUT", "DELETE");
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(source);
    }
}

這個配置與上面的全局跨域配置類似,但是通過CorsFilter提供了更多的靈活性和控制。

注意事項:

  • allowedOrigins可以是一個具體的域名,如"http://example.com",或者使用"*"來允許任何源。
  • allowedMethods定義了允許的HTTP方法。
  • allowCredentials設(shè)置為true時,服務(wù)器將接受包含敏感信息(如Cookies和HTTP認(rèn)證信息)的跨域請求。
  • allowedHeaders定義了允許的HTTP請求頭。

根據(jù)你的項目需求和安全考慮,合理配置跨域支持是非常重要的。

在生產(chǎn)環(huán)境中,通常不建議允許任何源("*"),而是應(yīng)該明確指定可信的源。

當(dāng)然,除了上述提到的使用@CrossOrigin注解、全局跨域配置和CorsFilter之外,還有其他一些方法可以在Spring Boot項目中配置跨域支持。

4. 配置WebMvcConfigurerProperties

在Spring Boot中,可以通過擴展WebMvcConfigurerProperties類來配置跨域。

首先,需要創(chuàng)建一個配置類并繼承WebMvcConfigurerProperties

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ConfigurationProperties(prefix = "cors")
public class CorsConfig implements WebMvcConfigurer {

    private String[] allowedOrigins;
    private String[] allowedMethods;
    private String[] allowedHeaders;
    private boolean allowCredentials;

    // getters and setters ...

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(allowedOrigins)
                .allowedMethods(allowedMethods)
                .allowedHeaders(allowedHeaders)
                .allowCredentials(allowCredentials);
    }
}

然后,在application.propertiesapplication.yml中添加相應(yīng)的配置:

# application.properties
cors.allowedOrigins[0]=http://example.com
cors.allowedMethods[0]=GET
cors.allowedMethods[1]=POST
cors.allowedHeaders[0]=Content-Type
cors.allowCredentials=true

5. 使用Spring Security

如果你的項目中使用了Spring Security,可以通過配置HttpSecurity來實現(xiàn)跨域支持。

首先,需要創(chuàng)建一個配置類并重寫configure(HttpSecurity http)方法:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...其他配置...
            .cors().and() // 啟用默認(rèn)的跨域配置
            // ...其他配置...
    }
}

如果需要自定義跨域配置,可以使用.cors()方法并傳遞一個CorsConfigurationSource實例:

 CorsConfiguration configuration = new CorsConfiguration();
 configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
 configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE"));
 configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
 configuration.setAllowCredentials(true);

 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
 source.registerCorsConfiguration("/**", configuration);

 http.cors(source).and();

6. 使用第三方庫

還可以使用第三方庫如cors-filter來實現(xiàn)跨域支持。

這通常需要在項目的pom.xml中添加依賴,并在web.xml中配置過濾器。

以上是一些在Spring Boot項目中配置跨域支持的方法。

選擇最適合項目需求和架構(gòu)的方法,并確保考慮到安全性和性能的影響。

在實施跨域策略時,應(yīng)當(dāng)避免過度寬松的配置,以免引入安全風(fēng)險。

這些僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 深入理解happens-before和as-if-serial語義

    深入理解happens-before和as-if-serial語義

    本文大部分整理自《Java并發(fā)編程的藝術(shù)》,溫故而知新,加深對基礎(chǔ)的理解程度。下面可以和小編來一起學(xué)習(xí)下
    2019-05-05
  • Java實現(xiàn)字符串拆分的三種方法詳解

    Java實現(xiàn)字符串拆分的三種方法詳解

    字符串拆分,看似簡單的操作,背后卻隱藏著性能的玄機,本文將和大家詳細(xì)介紹一下三種Java實現(xiàn)字符串拆分的方法,有需要的小伙伴可以參考一下
    2026-02-02
  • Mybatis Plugin攔截器開發(fā)過程詳解

    Mybatis Plugin攔截器開發(fā)過程詳解

    這篇文章主要介紹了Mybatis Plugin攔截器開發(fā)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • Java?18?新特性之Web服務(wù)器?jwebserver功能

    Java?18?新特性之Web服務(wù)器?jwebserver功能

    JEP?408:?Simple?Web?Server,是這次Java?18推出的一個比較獨立的全新功能點。我們可以通過命令行工具來啟動一個提供靜態(tài)資源訪問的迷你Web服務(wù)器,本文通過一個構(gòu)建HTML頁面的例子,來嘗試一下jwebserver的功能
    2022-04-04
  • Java SpringBoot 集成 Redis詳解

    Java SpringBoot 集成 Redis詳解

    Redis 是一個由 Salvatore Sanfilippo 寫的 key-value 存儲系統(tǒng),是跨平臺的非關(guān)系型數(shù)據(jù)庫。Redis 是一個開源的使用 ANSI C 語言編寫、遵守 BSD 協(xié)議、支持網(wǎng)絡(luò)、可基于內(nèi)存、分布式、可選持久性的鍵值對(Key-Value)存儲數(shù)據(jù)庫,并提供多種語言的 API
    2021-10-10
  • Java LinkedList集合功能實例解析

    Java LinkedList集合功能實例解析

    這篇文章主要介紹了Java LinkedList集合功能實例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • SpringBoot中使用Redis對接口進行限流的實現(xiàn)

    SpringBoot中使用Redis對接口進行限流的實現(xiàn)

    本文將結(jié)合實例代碼,介紹SpringBoot中使用Redis對接口進行限流的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • 如何在JAVA中使用Synchronized

    如何在JAVA中使用Synchronized

    這篇文章主要介紹了如何在JAVA中使用Synchronized,文中代碼非常詳細(xì),對大家的學(xué)習(xí)有所幫助,感興趣的朋友可以參考下
    2020-06-06
  • Java中Object和內(nèi)部類舉例詳解

    Java中Object和內(nèi)部類舉例詳解

    這篇文章主要介紹了Java中Object和內(nèi)部類的相關(guān)資料,Object類是Java中所有類的父類,提供了toString、hashCode和equals等方法,內(nèi)部類分為實例內(nèi)部類、靜態(tài)內(nèi)部類、匿名內(nèi)部類和局部內(nèi)部類,需要的朋友可以參考下
    2025-05-05
  • MyBatis使用annonation定義類型映射的簡易用法示例

    MyBatis使用annonation定義類型映射的簡易用法示例

    這篇文章主要介紹了MyBatis使用annonation定義類型映射的簡易用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-09-09

最新評論

雅江县| 彰化县| 盐亭县| 共和县| 南部县| 红原县| 砀山县| 来安县| 佛坪县| 建宁县| 青田县| 辛集市| 图片| 肇庆市| 江孜县| 湖口县| 上栗县| 安仁县| 鲜城| 宿迁市| 旬阳县| 南昌县| 沿河| 基隆市| 江川县| 沅江市| 绥化市| 梨树县| 安阳市| 连平县| 三江| 舟曲县| 铅山县| 巧家县| 金寨县| 长寿区| 鞍山市| 浠水县| 邵东县| 花莲县| 饶平县|