Spring MVC 4支持跨域请求配置功能,可以通过简单的配置允许服务资源被跨域请求。
1、跨域请求数据
跨域请求数据在controller的方法上使用注解
@CrossOrigin(origins = "*", maxAge = 3600, methods={RequestMethod.POST,RequestMethod.GET})
注:methods必须配置,在使用4.3版本时,不配置methods无法请求到数据,原因是默认为空数组,不允许任何请求方式
2、跨域请求静态资源
需要在xml文件中增加如下配置:
<!-- API 接口跨域配置 -->
<mvc:cors>
<mvc:mapping path="/static/**"
allowed-origins="*"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
/>
</mvc:cors>
<!-- 静态资源映射 -->
<mvc:resources mapping="/static/**" location="/static/"/>
备注:http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd