SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域

时间:2023-03-09 04:34:31
SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域

SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

©Copyright 蕃薯耀 2017年7月14日

http://www.cnblogs.com/fanshuyao/

一、SpringMvc跨域支持

从Spring MVC 4.2 开始增加支持跨域访问

二、使用方法

1、某个方法支持跨域访问

在方法上增加@CrossOrigin注解,如下:

  1. @RequestMapping("/crossDomain2")
  2. @ResponseBody
  3. @CrossOrigin
  4. public String crossDomain2(HttpServletRequest req, HttpServletResponse res, String name){
  5. ……
  6. ……
  7. }

其中@CrossOrigin中的2个参数:

origins  : 允许可访问的域列表

  1. List of allowed origins, e.g. "http://domain1.com".
  2. These values are placed in the Access-Control-Allow-Origin header of both the pre-flight response and the actual response. "*" means that all origins are allowed.
  3. If undefined, all origins are allowed.

 maxAge:飞行前响应的缓存持续时间的最大年龄(以秒为单位)。

  1. The maximum age (in seconds) of the cache duration for pre-flight responses.
  2. This property controls the value of the Access-Control-Max-Age header in the pre-flight response.
  3. Setting this to a reasonable value can reduce the number of pre-flight request/response interactions required by the browser. A negative value means undefined.
  4. If undefined, max age is set to 1800 seconds (i.e., 30 minutes).

2、整个Controller都支持跨域访问,在类上面加上注解@CrossOrigin,如下:

  1. @Controller
  2. @CrossOrigin
  3. public class TestController {
  4. ……
  5. ……
  6. }

3、自定义规则支持全局跨域访问,在spring-mvc.xml文件中配置映射路径,如下:

  1. <mvc:cors>
  2. <mvc:mapping path="/cross/*"/>
  3. </mvc:cors>

上面表示有/cross/路径的请求都支持跨域访问,也可以增加其它的,如下:

  1. <mvc:cors>
  2. <mvc:mapping path="/cross/*" allowed-origins="" max-age="2500"/>
  3. <mvc:mapping path="/domain/*"/>
  4. </mvc:cors>

请求路径有/cross/,方法示例如下:

  1. @RequestMapping("/cross/crossDomain")
  2. @ResponseBody
  3. public String crossDomain(HttpServletRequest req, HttpServletResponse res, String name){
  4. ……
  5. ……
  6. }

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

©Copyright 蕃薯耀 2017年7月14日

http://www.cnblogs.com/fanshuyao/