Spring MVC中跨域问题处理

打印 上一主题 下一主题

主题 1940|帖子 1940|积分 5820

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在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. }
复制代码


  • 参数说明

    • origins: 允许的源(多个用逗号分隔,或用 @CrossOrigin(origins = "*") 允许全部,但不保举生产情况)。
    • methods: 允许的HTTP方法(如 RequestMethod.GET)。
    • allowedHeaders: 允许的哀求头。
    • allowCredentials: 是否允许发送Cookie(需与前端配置同等)。


方法二:全局配置 WebMvcConfigurer

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


  • 创建配置类实现 WebMvcConfigurer。
  • 重写 addCorsMappings 方法。
示例代码:

  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。
步骤:


  • 在安全配置类中启用CORS。
  • 定义 CorsConfigurationSource Bean。
示例代码:

  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 配置方式,实用于全局跨域设置。
步骤:


  • 确保 XML 文件头部声明白 mvc 命名空间
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4.        xmlns:mvc="http://www.springframework.org/schema/mvc"
    5.        xsi:schemaLocation="
    6.            http://www.springframework.org/schema/beans
    7.            http://www.springframework.org/schema/beans/spring-beans.xsd
    8.            http://www.springframework.org/schema/mvc
    9.            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    复制代码
  • 在 <mvc:annotation-driven> 标签内配置跨域规则
    1. <mvc:annotation-driven>
    2.     <mvc:cors>
    3.         <!-- 配置全局跨域 -->
    4.         <mvc:mapping path="/**"
    5.                      allowed-origins="http://localhost:8080, https://example.com"
    6.                      allowed-methods="GET, POST, PUT, DELETE, OPTIONS"
    7.                      allowed-headers="Content-Type, Authorization"
    8.                      allow-credentials="true"
    9.                      max-age="3600"/>
    10.     </mvc:cors>
    11. </mvc:annotation-driven>
    复制代码

    • 参数说明

      • path: 匹配的 URL 路径模式(支持 Ant 风格,如 /api/**)。
      • allowed-origins: 允许的源(多个用逗号分隔)。
      • allowed-methods: 允许的 HTTP 方法。
      • allowed-headers: 允许的哀求头。
      • allow-credentials: 是否允许发送 Cookie(对应 allowCredentials(true))。
      • max-age: 预检哀求缓存时间(秒)。



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

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


  • 在 applicationContext.xml 中定义 CorsFilter Bean
    1. <bean id="corsFilter" class="org.springframework.web.filter.CorsFilter">
    2.     <constructor-arg>
    3.         <bean class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
    4.             <property name="corsConfigurations">
    5.                 <map>
    6.                     <entry key="/**">
    7.                         <bean class="org.springframework.web.cors.CorsConfiguration">
    8.                             <property name="allowedOrigins">
    9.                                 <list>
    10.                                     <value>http://localhost:8080</value>
    11.                                     <value>https://example.com</value>
    12.                                 </list>
    13.                             </property>
    14.                             <property name="allowedMethods">
    15.                                 <list>
    16.                                     <value>GET</value>
    17.                                     <value>POST</value>
    18.                                     <value>PUT</value>
    19.                                     <value>DELETE</value>
    20.                                     <value>OPTIONS</value>
    21.                                 </list>
    22.                             </property>
    23.                             <property name="allowedHeaders">
    24.                                 <list>
    25.                                     <value>Content-Type</value>
    26.                                     <value>Authorization</value>
    27.                                 </list>
    28.                             </property>
    29.                             <property name="allowCredentials" value="true"/>
    30.                             <property name="maxAge" value="3600"/>
    31.                         </bean>
    32.                     </entry>
    33.                 </map>
    34.             </property>
    35.         </bean>
    36.     </constructor-arg>
    37. </bean>
    复制代码
  • 确保 CorsFilter 优先实行
    在 web.xml 中,将 CorsFilter 注册为第一个 Filter:
    1. <filter>
    2.     <filter-name>corsFilter</filter-name>
    3.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    4. </filter>
    5. <filter-mapping>
    6.     <filter-name>corsFilter</filter-name>
    7.     <url-pattern>/*</url-pattern>
    8. </filter-mapping>
    复制代码

完备示例:结合 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。
关键注意事项


  • 预检哀求(Preflight):欣赏器会先发送 OPTIONS 哀求检查服务器是否允许跨域。确保配置中包含 allowedMethods 并精确处理 OPTIONS。
  • 携带凭据(Cookies):若需传输Cookies,前端需设置 withCredentials: true,后端需设置 allowCredentials(true),且 allowedOrigins 不能为 *。
  • 生产情况安全:避免使用通配符 *,应明白指定允许的源、方法和头信息。
  • allowedOrigins vs allowedOriginPatterns

    • 假如使用 Spring 5.3+,可以用 allowedOriginPatterns 支持通配符模式(如 http://*.example.com)。
    • XML 配置中需通过 <list> 手动指定详细域名。

  • 与 Spring Security 集成

    • 假如项目集成了 Spring Security,需在安全配置中启用 CORS:
      1. <http auto-config="true" use-expressions="true">
      2.     <cors/> <!-- 启用 CORS -->
      3.     <!-- 其他安全配置 -->
      4. </http>
      复制代码

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

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

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

一给

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表