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

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

 

一、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

  

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值