SpringMvc支持跨域訪問,Spring跨域訪問,SpringMvc @CrossOrigin 跨域
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年7月14日
http://www.cnblogs.com/fanshuyao/
一、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月14日
http://www.cnblogs.com/fanshuyao/