温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Spring Boot中配置CORS策略

发布时间:2024-10-05 14:27:03 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在Spring Boot应用程序中配置跨域资源共享(CORS)策略可以通过多种方式实现,以下是几种常见的方法:

方法一:使用@CrossOrigin注解

你可以在控制器类或方法上使用@CrossOrigin注解来配置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!";
    }
}

在这个例子中,@CrossOrigin注解指定了允许的源(origins),这里是http://localhost:8080

方法二:全局CORS配置

你也可以在Spring Boot应用程序中配置全局的CORS策略。这可以通过实现WebMvcConfigurer接口来完成。例如:

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);
    }
}

在这个例子中,addCorsMappings方法定义了全局的CORS策略。/**表示允许所有路径,allowedOrigins指定了允许的源,allowedMethods指定了允许的HTTP方法,allowedHeaders指定了允许的请求头,allowCredentials表示是否允许发送Cookie。

方法三:使用Filter实现CORS

你还可以通过自定义一个Filter来实现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配置类中注册这个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;
    }
}

在这个例子中,FilterRegistrationBean用于注册自定义的CorsFilter,并指定它应该应用于所有URL模式。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI