SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域[转]

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

原文地址:https://www.cnblogs.com/fanshuyao/p/7168471.htmlspring

©Copyright 蕃薯耀 2017年7月14日跨域

http://www.cnblogs.com/fanshuyao/spring-mvc

1、SpringMvc跨域支持缓存

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

2、使用方法app

一、某个方法支持跨域访问cors

在方法上增长@CrossOrigin注解,以下:dom

Java代码
@RequestMapping("/crossDomain2")
@ResponseBody
@CrossOrigin
public String crossDomain2(HttpServletRequest req, HttpServletResponse res, String name){
……
……
}
其中@CrossOrigin中的2个参数:ui

origins : 容许可访问的域列表

Java代码
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:飞行前响应的缓存持续时间的最大年龄(以秒为单位)。

Java代码
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).

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

Java代码
@Controller
@CrossOrigin
public class TestController {
……
……
}

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

Java代码


若是整个项目全部方法均可以访问,则能够这样配置

Xml代码



其中* 表示匹配到下一层

** 表示后面无论有多少层,都能匹配。

如:

Java代码



这个能够匹配到的路径有:

/cross/aaa

/cross/bbbb

不能匹配的:

/corss/aaa/bbb

由于* 只能匹配到下一层路径,若是想后面无论多少层均可以匹配,配置以下:

Xml代码



就是一颗星(*) 变成两颗星(**)

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

Java代码




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

Java代码
@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

相关文章
相关标签/搜索