qidao123.com技术社区-IT企服评测·应用市场

标题: Spring MVC中跨域问题处理 [打印本页]

作者: 一给    时间: 2025-5-8 11:13
标题: Spring MVC中跨域问题处理
在Spring MVC中处理跨域问题可以通过以下几种方式实现,确保前后端能够正常通讯:

方法一:使用 @CrossOrigin 注解

实用于局部控制跨域配置,直接在Controller或方法上添加注解。
示例代码:

  1. @RestController
  2. @CrossOrigin(origins = "http://localhost:8080") // 允许指定源
  3. public class MyController {
  4.     @GetMapping("/data")
  5.     public String getData() {
  6.         return "Hello, CORS!";
  7.     }
  8. }
复制代码


方法二:全局配置 WebMvcConfigurer

实用于全局跨域设置,同一管理全部接口的跨域规则。
步骤:

示例代码:

  1. @Configuration
  2. public class CorsGlobalConfig implements WebMvcConfigurer {
  3.     @Override
  4.     public void addCorsMappings(CorsRegistry registry) {
  5.         registry.addMapping("/**") // 匹配所有路径
  6.                 .allowedOrigins("http://localhost:8080", "https://example.com")
  7.                 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
  8.                 .allowedHeaders("*")
  9.                 .allowCredentials(true)
  10.                 .maxAge(3600); // 预检请求缓存时间(秒)
  11.     }
  12. }
复制代码

方法三:使用 CorsFilter

通过自定义过滤器精致化控制跨域行为,得当复杂场景。
示例代码:

  1. @Configuration
  2. public class CorsFilterConfig {
  3.     @Bean
  4.     public CorsFilter corsFilter() {
  5.         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  6.         CorsConfiguration config = new CorsConfiguration();
  7.         config.setAllowCredentials(true);
  8.         config.addAllowedOrigin("http://localhost:8080");
  9.         config.addAllowedHeader("*");
  10.         config.addAllowedMethod("*");
  11.         source.registerCorsConfiguration("/**", config); // 对所有路径生效
  12.         return new CorsFilter(source);
  13.     }
  14. }
复制代码

方法四:结合 Spring Security

若项目集成了Spring Security,需额外配置安全规则以启用CORS。
步骤:

示例代码:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  4.     @Override
  5.     protected void configure(HttpSecurity http) throws Exception {
  6.         http.cors().and() // 启用CORS
  7.             .csrf().disable()
  8.             .authorizeRequests()
  9.             .anyRequest().authenticated();
  10.     }
  11.     @Bean
  12.     public CorsConfigurationSource corsConfigurationSource() {
  13.         CorsConfiguration config = new CorsConfiguration();
  14.         config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
  15.         config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
  16.         config.setAllowedHeaders(Arrays.asList("*"));
  17.         config.setAllowCredentials(true);
  18.         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  19.         source.registerCorsConfiguration("/**", config);
  20.         return source;
  21.     }
  22. }
复制代码

方法五:通过 <mvc:cors> 命名空间配置全局跨域规则

在 Spring MVC 中,假如项目使用 applicationContext.xml 举行配置(基于 XML 的配置方式),这是最直接的 XML 配置方式,实用于全局跨域设置。
步骤:


方法六:通过自定义 CorsFilter Bean 配置

通过applicationContext.xml配置处理跨域问题时,假如需要对跨域行为举行更细粒度的控制(比方动态配置),可以手动注册 CorsFilter。
步骤:


完备示例:结合 applicationContext.xml 和 web.xml

applicationContext.xml 配置:

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2.        xmlns:mvc="http://www.springframework.org/schema/mvc"
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.        xsi:schemaLocation="
  5.            http://www.springframework.org/schema/beans
  6.            http://www.springframework.org/schema/beans/spring-beans.xsd
  7.            http://www.springframework.org/schema/mvc
  8.            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  9.     <!-- 启用注解驱动并配置 CORS -->
  10.     <mvc:annotation-driven>
  11.         <mvc:cors>
  12.             <mvc:mapping path="/**"
  13.                          allowed-origins="http://localhost:8080"
  14.                          allowed-methods="GET, POST, PUT, DELETE"
  15.                          allowed-headers="Content-Type, Authorization"
  16.                          allow-credentials="true"
  17.                          max-age="3600"/>
  18.         </mvc:cors>
  19.     </mvc:annotation-driven>
  20. </beans>
复制代码
web.xml 配置(确保 Filter 顺序):

  1. <filter>
  2.     <filter-name>corsFilter</filter-name>
  3.     <filter-class>org.springframework.web.filter.CorsFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6.     <filter-name>corsFilter</filter-name>
  7.     <url-pattern>/*</url-pattern>
  8. </filter-mapping>
复制代码

通过方式五和方式六,可以在基于 XML 的 Spring MVC 项目中机动配置跨域规则。保举使用 <mvc:cors> 命名空间配置,简朴且直接;若需动态控制,则选择 CorsFilter。
关键注意事项

通过上述方法,可机动解决Spring MVC中的跨域问题,根据项目需求选择最合适的方案。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4