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

Spring?Boot3?跨域配置?Cors的方式

 更新時間:2024年01月15日 09:01:18   作者:Code技術(shù)分享  
這篇文章主要介紹了Spring?Boot3?跨域配置?Cors,通過使用CORS,開發(fā)人員可以控制哪些外部網(wǎng)頁可以訪問他們的資源,從而提高應(yīng)用程序的安全性,本文結(jié)合實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下

什么是CORS?

CORS,全稱是“跨源資源共享”(Cross-Origin Resource Sharing),是一種Web應(yīng)用程序的安全機(jī)制,用于控制不同源的資源之間的交互。

在Web應(yīng)用程序中,CORS定義了一種機(jī)制,通過該機(jī)制,瀏覽器能夠限制哪些外部網(wǎng)頁可以訪問來自不同源的資源。源由協(xié)議、域名和端口組成。當(dāng)一個網(wǎng)頁請求另一個網(wǎng)頁上的資源時,瀏覽器會檢查請求是否符合CORS規(guī)范,以確定是否允許該請求。

CORS的工作原理是:當(dāng)瀏覽器發(fā)送一個跨域請求時,它會附加一些額外的頭部信息到請求中,這些頭部信息包含了關(guān)于請求的來源和目的的信息。服務(wù)器可以檢查這些頭部信息并決定是否允許該請求。如果服務(wù)器允許請求,它會返回一個響應(yīng),其中包含一個名為“Access-Control-Allow-Origin”的頭部信息,該信息指定了哪些源可以訪問該資源。瀏覽器會檢查返回的“Access-Control-Allow-Origin”頭部信息,以確定是否允許該跨域請求。

通過使用CORS,開發(fā)人員可以控制哪些外部網(wǎng)頁可以訪問他們的資源,從而提高應(yīng)用程序的安全性。

Spring Boot 如何配置CORS?

Spring Boot對于跨域請求的支持可以通過兩種配置方式來實現(xiàn):

  • 注解配置:可以使用@CrossOrigin注解來啟用CORS。例如,在需要支持跨域請求的方法上添加@CrossOrigin注解,并配置好origins和maxAge等參數(shù)。
  • 全局配置:可以通過實現(xiàn)WebMvcConfigurer接口并注冊一個WebMvcConfigurer bean來配置CORS的全局設(shè)置。在實現(xiàn)類中覆蓋addCorsMappings方法,通過CorsRegistry對象添加映射規(guī)則。默認(rèn)情況下,所有方法都支持跨域,并且GET、POST和HEAD請求是被允許的。如果需要自定義,可以配置CorsRegistry對象來指定允許的域名、端口和請求方法等。
  • 過濾器配置:可以通過CorsFilter bean來配置CORS的過濾器。這種方式可以更加靈活地控制CORS的配置,例如只允許特定的域名進(jìn)行跨域訪問等。

前端代碼

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    <body>
        <script>
            $.ajax({
                url: 'http://localhost:8080/hello',
                type: 'GET',
                //xhrFields: { withCredentials: true }, //開啟認(rèn)證
                success: function (data) {
                    console.log(data)
                }
            })
        </script>
    </body>
</html>

注解配置

@CrossOrigin 是 Spring Framework 中的一個注解,用于處理跨域請求。當(dāng)一個前端頁面嘗試從不同的源(域名、端口或協(xié)議)請求數(shù)據(jù)時,瀏覽器的同源策略會阻止這種請求,以防止?jié)撛诘陌踩珕栴}。然而,在某些情況下,你可能希望允許跨域請求,這時就可以使用 @CrossOrigin 注解。

添加CorssOrigin注解

package com.mcode.springbootcorsdemo.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * ClassName: HelloController
 * Package: com.mcode.springbootcorsdemo.controller
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
@RestController
public class HelloController {
    @CrossOrigin(value = "http://127.0.0.1:5500",allowedHeaders = "*",allowCredentials = "true")
    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }
}

屬性:

@CrossOrigin 注解有幾個屬性,允許你更精細(xì)地控制跨域行為:

* origins: 允許的源列表,可以是域名、IP 或其他標(biāo)識符。多個源可以使用逗號分隔。  
* methods: 允許的 HTTP 方法列表。例如,只允許 GET 請求。  
* allowedHeaders: 允許的請求頭列表。默認(rèn)情況下,允許所有請求頭。  
* allowCredentials:是否允許配置;值為true、false的字符串
* maxAge: 預(yù)檢請求的緩存時間(以秒為單位)。默認(rèn)是 86400 秒(24小時)。這些屬性可以根據(jù)需要進(jìn)行組合和配置。
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
    @AliasFor("origins")
    String[] value() default {};
    @AliasFor("value")
    String[] origins() default {};
    String[] originPatterns() default {};
    String[] allowedHeaders() default {};
    String[] exposedHeaders() default {};
    RequestMethod[] methods() default {};
    String allowCredentials() default "";
    long maxAge() default -1L;
}

全局配置

addCorsMappings 是 Spring Boot 中用于配置跨域請求的方法。它允許你指定哪些路徑的請求需要進(jìn)行跨域處理,以及如何處理這些請求。

在 addCorsMappings 方法中,你可以使用 addMapping 方法來指定需要跨域處理的請求路徑。例如:

package com.mcode.springbootcorsdemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * ClassName: MyWebMvcConfigurer
 * Package: com.mcode.springbootcorsdemo.config
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允許所有請求路徑跨域訪問
                .allowCredentials(true) // 是否攜帶Cookie,默認(rèn)false
                .allowedHeaders("*") // 允許的請求頭類型
                .maxAge(3600)  // 預(yù)檢請求的緩存時間(單位:秒)
                .allowedMethods("*") // 允許的請求方法類型
                .allowedOrigins("http://127.0.0.1:5500"); // 允許哪些域名進(jìn)行跨域訪問
    }
}

過濾器配置

在Spring Boot中,CorsFilter用于處理跨域請求。它是一個過濾器,用于在Spring應(yīng)用程序中啟用CORS(跨源資源共享)支持。

package com.mcode.springbootcorsdemo.config;
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;
/**
 * ClassName: CorsConfig
 * Package: com.mcode.springbootcorsdemo.config
 * Description:
 *
 * @Author: robin
 * @Version: v1.0
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.addAllowedOrigin("http://127.0.0.1:5500");
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        return  new CorsFilter(source);
    }
}

注意事項

當(dāng)我們沒有配置跨域的時候會提示:

Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

當(dāng)我們開啟withCredentials:true的時候沒有配置allowCredentials為true會提示:

Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

當(dāng)我們在后端配置了allowCredentials(true)那么就不能配置allowedOrigins("*"),必須指定來源

jakarta.servlet.ServletException: Request processing failed: java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

到此這篇關(guān)于Spring Boot3 跨域配置 Cors的文章就介紹到這了,更多相關(guān)Spring Boot3 跨域配置 Cors內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring Aop 如何獲取參數(shù)名參數(shù)值

    Spring Aop 如何獲取參數(shù)名參數(shù)值

    這篇文章主要介紹了Spring Aop 如何獲取參數(shù)名參數(shù)值的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • SpringSecurity的TokenStore四種實現(xiàn)方式小結(jié)

    SpringSecurity的TokenStore四種實現(xiàn)方式小結(jié)

    本文主要介紹了SpringSecurity的TokenStore四種實現(xiàn)方式小結(jié),分別是InMemoryTokenStore,JdbcTokenStore,JwkTokenStore,RedisTokenStore,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • 在Spring?AI?中配置多個?LLM?客戶端的詳細(xì)過程

    在Spring?AI?中配置多個?LLM?客戶端的詳細(xì)過程

    本文探討了如何在單個Spring?AI應(yīng)用中集成多個LLM,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2025-10-10
  • Spring深入刨析聲明式事務(wù)注解的源碼

    Spring深入刨析聲明式事務(wù)注解的源碼

    在spring注解中,使用聲明式事務(wù),需要用到兩個核心的注解:@Transactional注解和@EnableTransactionManagement注解。將@Transactional注解加在方法上,@EnableTransactionManagement注解加在配置類上
    2022-07-07
  • Spring單數(shù)據(jù)源的配置詳解

    Spring單數(shù)據(jù)源的配置詳解

    spring數(shù)據(jù)源的配置網(wǎng)絡(luò)上有很多例子,這里我也來介紹一下單數(shù)據(jù)源配置的例子,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • 深入理解與應(yīng)用Java抽象類

    深入理解與應(yīng)用Java抽象類

    Java抽象類是一個非常重要的概念,它允許我們定義包含抽象方法和非抽象方法的類,并為子類提供通用的屬性和方法,本文給大家介紹Java抽象類的理解與應(yīng)用,感興趣的朋友一起看看吧
    2025-04-04
  • Spring?Security入門到深入實戰(zhàn)步驟詳解

    Spring?Security入門到深入實戰(zhàn)步驟詳解

    小明通過學(xué)習(xí)SpringSecurity,成功為自己的攝影網(wǎng)站添加了完整的登錄認(rèn)證鑒權(quán)功能,包括自定義用戶存儲、權(quán)限控制、自定義登錄頁、JWT集成以及OAuth2第三方登錄,并且對SpringSecurity有了深入的理解和認(rèn)識,喜歡的朋友跟隨小編一起學(xué)習(xí)吧
    2025-11-11
  • java使用jacob實現(xiàn)word轉(zhuǎn)pdf

    java使用jacob實現(xiàn)word轉(zhuǎn)pdf

    這篇文章主要為大家詳細(xì)介紹了java使用jacob實現(xiàn)word轉(zhuǎn)pdf,通過調(diào)用模板文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-12-12
  • java實現(xiàn)LRU緩存淘汰算法的方法

    java實現(xiàn)LRU緩存淘汰算法的方法

    LRU(Least recently used,最近最少使用)算法根據(jù)數(shù)據(jù)的歷史訪問記錄來進(jìn)行淘汰數(shù)據(jù),其核心思想是“如果數(shù)據(jù)最近被訪問過,那么將來被訪問的幾率也更高”。下面看下java實現(xiàn)LRU緩存淘汰算法的方法,一起看看吧
    2021-11-11
  • java 獲取路徑的各種方法(總結(jié))

    java 獲取路徑的各種方法(總結(jié))

    下面小編就為大家?guī)硪黄猨ava 獲取路徑的各種方法(總結(jié))。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08

最新評論

克什克腾旗| 雷州市| 前郭尔| 甘孜县| 华安县| 基隆市| 阿城市| 凤城市| 宿迁市| 昌图县| 江陵县| 天水市| 青岛市| 永平县| 谷城县| 信宜市| 尉氏县| 邵东县| 仙游县| 厦门市| 富锦市| 高雄县| 顺平县| 喀什市| 松滋市| 克什克腾旗| 余江县| 松原市| 嘉黎县| 同江市| 富平县| 新昌县| 昭觉县| 鄂伦春自治旗| 永春县| 阿巴嘎旗| 金阳县| 高台县| 霍林郭勒市| 宣化县| 鸡西市|