欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Spring Boot 跨域解决方案

Spring Boot 跨域解决方案

2025/2/6 0:03:20 来源:https://blog.csdn.net/weixin_43738764/article/details/143382754  浏览:    关键词:Spring Boot 跨域解决方案

Spring Boot 跨域解决方案

引言

在 Web 应用中,跨域请求已经成为一个常见的问题。浏览器出于安全考虑,限制了不同源之间的请求,这种限制被称为同源策略。当我们的前端应用和后端 API 部署在不同的域名或端口下时,就会出现跨域问题。为了保证应用的正常运行,解决跨域问题显得尤为重要。本文将介绍两种常见的 Spring Boot 跨域解决方案:WebMvcConfigurerFilterRegistrationBean

常见的跨域产生条件:

  • 不同的协议:例如,前端使用 HTTPS,后端使用 HTTP。
  • 不同的域名:例如,前端在 example.com,后端在 api.example.com
  • 不同的端口:例如,前端在 localhost:3000,后端在 localhost:8080

1. 使用 WebMvcConfigurer 解决跨域

什么是 WebMvcConfigurer?

WebMvcConfigurer 是 Spring MVC 提供的一个接口,允许我们通过实现该接口来定制 Spring MVC 的配置。它提供了一系列钩子方法,便于我们进行全局配置。

实现跨域配置的步骤

下面是通过实现 WebMvcConfigurer 接口来配置跨域的示例代码:

@Configuration
public class SpringMvcConfiguration implements WebMvcConfigurer{@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowCredentials(true).allowedOrigins("*").allowedHeaders("*").allowedMethods("*").maxAge(1800L);}}

注意事项

  • allowedOrigins:可以指定允许的来源,可以是特定的域名。
  • allowedMethods:指定允许的 HTTP 方法,需根据实际需求配置。
  • allowedHeaders:指定允许的请求头,使用 "*" 表示允许所有请求头,具体可以根据需求进行限制。
  • allowCredentials:是否允许携带凭据(如 Cookies)。

2. 使用 FilterRegistrationBean 解决跨域

什么是 FilterRegistrationBean?

FilterRegistrationBean 是 Spring Boot 提供的用于注册过滤器的工具。通过注册自定义的过滤器,我们可以灵活地处理请求和响应,包括设置跨域相关的响应头。

实现跨域配置的步骤

以下是通过 FilterRegistrationBean 实现跨域配置的示例代码:

@Configuration
public class CorsConfig {@Beanpublic FilterRegistrationBean<CorsFilter> corsFilterBean() {CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.setAllowCredentials(true);corsConfiguration.addAllowedOrigin("*");corsConfiguration.addAllowedHeader("*");corsConfiguration.addAllowedMethod("*");corsConfiguration.setMaxAge(1800L);UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", corsConfiguration);FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));bean.setOrder(Integer.MIN_VALUE);return bean;}}

结论

本文介绍了两种在 Spring Boot 中处理跨域请求的方法:使用 WebMvcConfigurerFilterRegistrationBeanWebMvcConfigurer 方法相对简单,适合大多数场景;而 FilterRegistrationBean 方法提供了更大的灵活性,适合需要定制化处理的场景。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com