SpringMvc跨域

SpringMvc跨域

一、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文件中配置映射路径,如下:



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




请求路径有/cross/,方法示例如下:
@RequestMapping(“/cross/crossDomain”)
@ResponseBody
public String crossDomain(HttpServletRequest req, HttpServletResponse res, String name){
……
……
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值