溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Boot中的跨域資源共享配置

發(fā)布時(shí)間:2024-10-05 09:01:00 來源:億速云 閱讀:81 作者:小樊 欄目:編程語言

在Spring Boot中,我們可以使用@CrossOrigin注解來實(shí)現(xiàn)跨域資源共享(CORS)的配置。這個(gè)注解可以應(yīng)用在Controller類或者方法上。以下是一些常見的配置方式:

  1. 全局配置

在Spring Boot 2.x中,你可以通過創(chuàng)建一個(gè)配置類并使用@EnableWebMvcWebMvcConfigurer接口來實(shí)現(xiàn)全局的CORS配置。例如:

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

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

注意:allowedOrigins("*")表示允許所有來源,這在生產(chǎn)環(huán)境中可能不安全。你應(yīng)該指定具體的、可信的來源域名。 2. 局部配置

你也可以在Controller類或方法上直接使用@CrossOrigin注解來實(shí)現(xiàn)局部的CORS配置。例如:

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

@RestController
public class MyController {

    @CrossOrigin(origins = "http://example.com")
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

在這個(gè)例子中,只有來自http://example.com的請(qǐng)求才會(huì)被允許訪問/hello端點(diǎn)。 3. 過濾器的配置

另外,你還可以通過配置一個(gè)全局的CORS過濾器來實(shí)現(xiàn)CORS。例如:

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;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CorsFilter());
        registration.addUrlPatterns("/*");
        registration.setAllowedOrigins("*");
        registration.setAllowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
        registration.setAllowedHeaders("*");
        registration.setAllowCredentials(true);
        registration.setMaxAge(3600);
        return registration;
    }
}

這種方式與全局配置類似,但使用了過濾器來實(shí)現(xiàn)CORS。

請(qǐng)注意,上述示例中的配置可能不適用于所有場(chǎng)景。在生產(chǎn)環(huán)境中,你應(yīng)該根據(jù)具體需求和安全考慮來調(diào)整CORS配置。例如,避免使用allowedOrigins("*"),而是指定具體的、可信的來源域名。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI