Spring MVC中通过ApplicationContext.xml配置CORS失败排查
解决Spring MVC XML配置CORS导致构建失败的问题
先排查几个核心问题:
- 缺少mvc命名空间声明:你用了
<mvc:cors>标签,但如果ApplicationContext.xml头部没引入mvc命名空间,容器根本识别不了这些标签,直接会触发构建报错。 - 配置过于简略:仅指定
path="/**"在部分Spring版本里不被允许,必须补充必要的CORS属性才能正常解析。 - Spring版本过低:
<mvc:cors>是Spring 4.2及以后才支持的特性,用低于这个版本的框架肯定会失败。
给你一个完整可运行的XML配置示例:
首先在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">
然后添加完整的CORS配置:
<mvc:cors> <mvc:mapping path="/**" allowed-origins="http://localhost:3000" <!-- 替换成你的React实际运行地址 --> allowed-methods="GET, POST, PUT, DELETE, OPTIONS" allowed-headers="*" allow-credentials="true"/> </mvc:cors>
说明:
allowed-origins:指定允许跨域的前端域名,比如React默认跑在localhost:3000就填这个,生产环境换成实际域名。allowed-methods:必须包含OPTIONS,因为跨域预检请求会用这个方法。allow-credentials:如果前端需要携带Cookie或认证信息,设为true。
如果是Spring版本过低导致的问题,换用过滤器方式配置CORS(同样纯XML实现):
<filter> <filter-name>CorsFilter</filter-name> <filter-class>org.springframework.web.filter.CorsFilter</filter-class> <init-param> <param-name>corsConfigurationSource</param-name> <bean class="org.springframework.web.cors.UrlBasedCorsConfigurationSource"> <property name="corsConfigurations"> <map> <entry key="/**"> <bean class="org.springframework.web.cors.CorsConfiguration"> <property name="allowedOrigins" value="http://localhost:3000"/> <property name="allowedMethods" value="GET,POST,PUT,DELETE,OPTIONS"/> <property name="allowedHeaders" value="*"/> <property name="allowCredentials" value="true"/> </bean> </entry> </map> </property> </bean> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
内容的提问来源于stack exchange,提问作者Bilal Kundi
相关产品推荐
相关产品推荐

