溫馨提示×

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

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

如何在Spring Boot中配置CORS策略

發(fā)布時(shí)間:2024-10-05 14:27:03 來(lái)源:億速云 閱讀:81 作者:小樊 欄目:編程語(yǔ)言

在Spring Boot應(yīng)用程序中配置跨域資源共享(CORS)策略可以通過(guò)多種方式實(shí)現(xiàn),以下是幾種常見的方法:

方法一:使用@CrossOrigin注解

你可以在控制器類或方法上使用@CrossOrigin注解來(lái)配置CORS策略。例如:

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://localhost:8080")
public class MyController {

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

在這個(gè)例子中,@CrossOrigin注解指定了允許的源(origins),這里是http://localhost:8080。

方法二:全局CORS配置

你也可以在Spring Boot應(yīng)用程序中配置全局的CORS策略。這可以通過(guò)實(shí)現(xiàn)WebMvcConfigurer接口來(lái)完成。例如:

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

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

在這個(gè)例子中,addCorsMappings方法定義了全局的CORS策略。/**表示允許所有路徑,allowedOrigins指定了允許的源,allowedMethods指定了允許的HTTP方法,allowedHeaders指定了允許的請(qǐng)求頭,allowCredentials表示是否允許發(fā)送Cookie。

方法三:使用Filter實(shí)現(xiàn)CORS

你還可以通過(guò)自定義一個(gè)Filter來(lái)實(shí)現(xiàn)CORS策略。例如:

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    // 其他必要的方法,如init()和destroy()
}

然后,你需要在Spring Boot配置類中注冊(cè)這個(gè)Filter:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyAppConfig {

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CorsFilter());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

在這個(gè)例子中,FilterRegistrationBean用于注冊(cè)自定義的CorsFilter,并指定它應(yīng)該應(yīng)用于所有URL模式。

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

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

AI