`

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

阅读更多

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

 

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

©Copyright 蕃薯耀 2017年7月12日

http://fanshuyao.iteye.com/

 

一、SpringMvc跨域支持

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

 

二、使用方法

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

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

@RequestMapping("/crossDomain2")
@ResponseBody
@CrossOrigin
public String crossDomain2(HttpServletRequest req, HttpServletResponse res, String name){
    ……
    ……
}

 其中@CrossOrigin中的2个参数:

origins  : 允许可访问的域列表

List of allowed origins, e.g. "http://domain1.com". 
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. 

If undefined, all origins are allowed.

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

The maximum age (in seconds) of the cache duration for pre-flight responses. 
This property controls the value of the Access-Control-Max-Age header in the pre-flight response. 

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. 

If undefined, max age is set to 1800 seconds (i.e., 30 minutes).

 

 

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

@Controller
@CrossOrigin
public class TestController {
    ……
    ……
}

 

 

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

<mvc:cors>
    <mvc:mapping path="/cross/*"/>
</mvc:cors>

 

如果整个项目所有方法都可以访问,则可以这样配置

<mvc:cors>  
    <mvc:mapping path="/**"/>  
</mvc:cors> 

其中* 表示匹配到下一层

** 表示后面不管有多少层,都能匹配。

如:

<mvc:cors>
    <mvc:mapping path="/cross/*"/>
</mvc:cors>

这个可以匹配到的路径有:

/cross/aaa

/cross/bbbb

不能匹配的:

/corss/aaa/bbb

因为* 只能匹配到下一层路径,如果想后面不管多少层都可以匹配,配置如下:

 

<mvc:cors>
    <mvc:mapping path="/cross/**"/>
</mvc:cors>
 就是一颗星(*) 变成两颗星(**)

 

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

<mvc:cors>
    <mvc:mapping path="/cross/**" allowed-origins="" max-age="2500"/>
    <mvc:mapping path="/domain/**"/>
</mvc:cors>

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

@RequestMapping("/cross/crossDomain")
@ResponseBody
public String crossDomain(HttpServletRequest req, HttpServletResponse res, String name){
    ……
    ……
}

 

 官方文档见:http://spring.io/blog/2015/06/08/cors-support-in-spring-framework

或者见附件的图片附件:CORS support in Spring Framework.png

 

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

©Copyright 蕃薯耀 2017年7月12日

http://fanshuyao.iteye.com/

  • 大小: 400.9 KB
2
1
分享到:
评论
1 楼 蕃薯耀 2017-07-12  
Spring跨域请求,SpringMvc跨域访问,SpringMvc @CrossOrigin 跨域

>>>>>>>
蕃薯耀

相关推荐

Global site tag (gtag.js) - Google Analytics