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

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

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

什么是CORS?

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

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

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

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

Spring Boot 如何配置CORS?

Spring Boot對(duì)于跨域請(qǐng)求的支持可以通過(guò)兩種配置方式來(lái)實(shí)現(xiàn):

  • 注解配置:可以使用@CrossOrigin注解來(lái)啟用CORS。例如,在需要支持跨域請(qǐng)求的方法上添加@CrossOrigin注解,并配置好origins和maxAge等參數(shù)。
  • 全局配置:可以通過(guò)實(shí)現(xiàn)WebMvcConfigurer接口并注冊(cè)一個(gè)WebMvcConfigurer bean來(lái)配置CORS的全局設(shè)置。在實(shí)現(xiàn)類中覆蓋addCorsMappings方法,通過(guò)CorsRegistry對(duì)象添加映射規(guī)則。默認(rèn)情況下,所有方法都支持跨域,并且GET、POST和HEAD請(qǐng)求是被允許的。如果需要自定義,可以配置CorsRegistry對(duì)象來(lái)指定允許的域名、端口和請(qǐng)求方法等。
  • 過(guò)濾器配置:可以通過(guò)CorsFilter bean來(lái)配置CORS的過(guò)濾器。這種方式可以更加靈活地控制CORS的配置,例如只允許特定的域名進(jìn)行跨域訪問(wè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 }, //開(kāi)啟認(rèn)證
                success: function (data) {
                    console.log(data)
                }
            })
        </script>
    </body>
</html>

注解配置

@CrossOrigin 是 Spring Framework 中的一個(gè)注解,用于處理跨域請(qǐng)求。當(dāng)一個(gè)前端頁(yè)面嘗試從不同的源(域名、端口或協(xié)議)請(qǐng)求數(shù)據(jù)時(shí),瀏覽器的同源策略會(huì)阻止這種請(qǐng)求,以防止?jié)撛诘陌踩珕?wèn)題。然而,在某些情況下,你可能希望允許跨域請(qǐng)求,這時(shí)就可以使用 @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 注解有幾個(gè)屬性,允許你更精細(xì)地控制跨域行為:

* origins: 允許的源列表,可以是域名、IP 或其他標(biāo)識(shí)符。多個(gè)源可以使用逗號(hào)分隔。  
* methods: 允許的 HTTP 方法列表。例如,只允許 GET 請(qǐng)求。  
* allowedHeaders: 允許的請(qǐng)求頭列表。默認(rèn)情況下,允許所有請(qǐng)求頭。  
* allowCredentials:是否允許配置;值為true、false的字符串
* maxAge: 預(yù)檢請(qǐng)求的緩存時(shí)間(以秒為單位)。默認(rèn)是 86400 秒(24小時(shí))。這些屬性可以根據(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 中用于配置跨域請(qǐng)求的方法。它允許你指定哪些路徑的請(qǐng)求需要進(jìn)行跨域處理,以及如何處理這些請(qǐng)求。

在 addCorsMappings 方法中,你可以使用 addMapping 方法來(lái)指定需要跨域處理的請(qǐng)求路徑。例如:

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("/**") // 允許所有請(qǐng)求路徑跨域訪問(wèn)
                .allowCredentials(true) // 是否攜帶Cookie,默認(rèn)false
                .allowedHeaders("*") // 允許的請(qǐng)求頭類型
                .maxAge(3600)  // 預(yù)檢請(qǐng)求的緩存時(shí)間(單位:秒)
                .allowedMethods("*") // 允許的請(qǐng)求方法類型
                .allowedOrigins("http://127.0.0.1:5500"); // 允許哪些域名進(jìn)行跨域訪問(wèn)
    }
}

過(guò)濾器配置

在Spring Boot中,CorsFilter用于處理跨域請(qǐng)求。它是一個(gè)過(guò)濾器,用于在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);
    }
}

注意事項(xiàng)

當(dāng)我們沒(méi)有配置跨域的時(shí)候會(huì)提示:

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)我們開(kāi)啟withCredentials:true的時(shí)候沒(méi)有配置allowCredentials為true會(huì)提示:

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)我們?cè)诤蠖伺渲昧?code>allowCredentials(true)那么就不能配置allowedOrigins("*"),必須指定來(lái)源

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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

最新評(píng)論

德化县| 西乡县| 佛学| 绥阳县| 平顺县| 洪湖市| 察雅县| 晋州市| 海原县| 隆回县| 德兴市| 苏尼特右旗| 邢台市| 峨眉山市| 三原县| 凭祥市| 阿拉善左旗| 乌拉特前旗| 武清区| 北海市| 新泰市| 石台县| 贞丰县| 石楼县| 淮阳县| 离岛区| 德清县| 沐川县| 英吉沙县| 自贡市| 莫力| 揭东县| 合作市| 兴隆县| 宁国市| 华蓥市| 昭苏县| 曲沃县| 长宁县| 临洮县| 博乐市|