Spring MVC中跨域问题处理

在Spring MVC中处理跨域问题可以通过以下几种方式实现,确保前后端能够正常通信:


方法一:使用 @CrossOrigin 注解

适用于局部控制跨域配置,直接在Controller或方法上添加注解。

示例代码:
java 复制代码
@RestController
@CrossOrigin(origins = "http://localhost:8080") // 允许指定源
public class MyController {

    @GetMapping("/data")
    public String getData() {
        return "Hello, CORS!";
    }
}
  • 参数说明
    • origins: 允许的源(多个用逗号分隔,或用 @CrossOrigin(origins = "*") 允许所有,但不推荐生产环境)。
    • methods: 允许的HTTP方法(如 RequestMethod.GET)。
    • allowedHeaders: 允许的请求头。
    • allowCredentials: 是否允许发送Cookie(需与前端配置一致)。

方法二:全局配置 WebMvcConfigurer

适用于全局跨域设置,统一管理所有接口的跨域规则。

步骤:
  1. 创建配置类实现 WebMvcConfigurer
  2. 重写 addCorsMappings 方法。
示例代码:
java 复制代码
@Configuration
public class CorsGlobalConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 匹配所有路径
                .allowedOrigins("http://localhost:8080", "https://example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600); // 预检请求缓存时间(秒)
    }
}

方法三:使用 CorsFilter

通过自定义过滤器精细化控制跨域行为,适合复杂场景。

示例代码:
java 复制代码
@Configuration
public class CorsFilterConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:8080");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config); // 对所有路径生效
        return new CorsFilter(source);
    }
}

方法四:结合 Spring Security

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

步骤:
  1. 在安全配置类中启用CORS。
  2. 定义 CorsConfigurationSource Bean。
示例代码:
java 复制代码
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and() // 启用CORS
            .csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

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

在 Spring MVC 中,如果项目使用 applicationContext.xml 进行配置(基于 XML 的配置方式),这是最直接的 XML 配置方式,适用于全局跨域设置。

步骤:
  1. 确保 XML 文件头部声明了 mvc 命名空间

    xml 复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="
               http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/mvc
               http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  2. <mvc:annotation-driven> 标签内配置跨域规则

    xml 复制代码
    <mvc:annotation-driven>
        <mvc:cors>
            <!-- 配置全局跨域 -->
            <mvc:mapping path="/**"
                         allowed-origins="http://localhost:8080, https://example.com"
                         allowed-methods="GET, POST, PUT, DELETE, OPTIONS"
                         allowed-headers="Content-Type, Authorization"
                         allow-credentials="true"
                         max-age="3600"/>
        </mvc:cors>
    </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

步骤:
  1. applicationContext.xml 中定义 CorsFilter Bean

    xml 复制代码
    <bean id="corsFilter" class="org.springframework.web.filter.CorsFilter">
        <constructor-arg>
            <bean class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
                <property name="corsConfigurations">
                    <map>
                        <entry key="/**">
                            <bean class="org.springframework.web.cors.CorsConfiguration">
                                <property name="allowedOrigins">
                                    <list>
                                        <value>http://localhost:8080</value>
                                        <value>https://example.com</value>
                                    </list>
                                </property>
                                <property name="allowedMethods">
                                    <list>
                                        <value>GET</value>
                                        <value>POST</value>
                                        <value>PUT</value>
                                        <value>DELETE</value>
                                        <value>OPTIONS</value>
                                    </list>
                                </property>
                                <property name="allowedHeaders">
                                    <list>
                                        <value>Content-Type</value>
                                        <value>Authorization</value>
                                    </list>
                                </property>
                                <property name="allowCredentials" value="true"/>
                                <property name="maxAge" value="3600"/>
                            </bean>
                        </entry>
                    </map>
                </property>
            </bean>
        </constructor-arg>
    </bean>
  2. 确保 CorsFilter 优先执行

    web.xml 中,将 CorsFilter 注册为第一个 Filter:

    xml 复制代码
    <filter>
        <filter-name>corsFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>corsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

完整示例:结合 applicationContext.xmlweb.xml

applicationContext.xml 配置:
xml 复制代码
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 启用注解驱动并配置 CORS -->
    <mvc:annotation-driven>
        <mvc:cors>
            <mvc:mapping path="/**"
                         allowed-origins="http://localhost:8080"
                         allowed-methods="GET, POST, PUT, DELETE"
                         allowed-headers="Content-Type, Authorization"
                         allow-credentials="true"
                         max-age="3600"/>
        </mvc:cors>
    </mvc:annotation-driven>

</beans>
web.xml 配置(确保 Filter 顺序):
xml 复制代码
<filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>org.springframework.web.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

通过方式五和方式六,可以在基于 XML 的 Spring MVC 项目中灵活配置跨域规则。推荐使用 <mvc:cors> 命名空间配置,简单且直接;若需动态控制,则选择 CorsFilter

关键注意事项

  1. 预检请求(Preflight) :浏览器会先发送 OPTIONS 请求检查服务器是否允许跨域。确保配置中包含 allowedMethods 并正确处理 OPTIONS
  2. 携带凭证(Cookies) :若需传输Cookies,前端需设置 withCredentials: true,后端需设置 allowCredentials(true),且 allowedOrigins 不能为 *
  3. 生产环境安全 :避免使用通配符 *,应明确指定允许的源、方法和头信息。
  4. allowedOrigins vs allowedOriginPatterns
    • 如果使用 Spring 5.3+,可以用 allowedOriginPatterns 支持通配符模式(如 http://*.example.com)。
    • XML 配置中需通过 <list> 手动指定具体域名。
  5. 与 Spring Security 集成
    • 如果项目集成了 Spring Security,需在安全配置中启用 CORS:

      xml 复制代码
      <http auto-config="true" use-expressions="true">
          <cors/> <!-- 启用 CORS -->
          <!-- 其他安全配置 -->
      </http>

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

相关推荐
bxp132117 分钟前
springboot国家化多语言实现
java·spring boot·后端
纪元A梦30 分钟前
贪心算法应用:边着色问题详解
java·算法·贪心算法
工业互联网专业1 小时前
基于springboot+vue的社区药房系统
java·vue.js·spring boot·毕业设计·源码·课程设计·社区药房系统
API小爬虫2 小时前
如何用爬虫获得按关键字搜索淘宝商品
java·爬虫·python
sanx182 小时前
从零搭建体育比分网站完整步骤
java·开发语言
夏季疯2 小时前
学习笔记:黑马程序员JavaWeb开发教程(2025.3.29)
java·笔记·学习
努力也学不会java3 小时前
【HTTP】《HTTP 全原理解析:从请求到响应的奇妙之旅》
java·网络·网络协议·http
Ten peaches3 小时前
苍穹外卖(订单状态定时处理、来单提醒和客户催单)
java·数据库·sql·springboot
caihuayuan53 小时前
全文索引数据库Elasticsearch底层Lucene
java·大数据·vue.js·spring boot·课程设计
冼紫菜3 小时前
Spring 项目无法连接 MySQL:Nacos 配置误区排查与解决
java·spring boot·后端·mysql·docker·springcloud