SpringMvc支援跨域通路,Spring跨域通路,SpringMvc @CrossOrigin 跨域
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年7月14日
http://www.cnblogs.com/fanshuyao/
一、SpringMvc跨域支援
從Spring MVC 4.2 開始增加支援跨域通路
二、使用方法
1、某個方法支援跨域通路
在方法上增加@CrossOrigin注解,如下:
Java代碼

@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
public class TestController {
3、自定義規則支援全局跨域通路,在spring-mvc.xml檔案中配置映射路徑,如下:

<mvc:cors>
<mvc:mapping path="/cross/*"/>
</mvc:cors>
如果整個項目所有方法都可以通路,則可以這樣配置
Xml代碼

<mvc:cors>
<mvc:mapping path="/**"/>
</mvc:cors>
其中* 表示比對到下一層
** 表示後面不管有多少層,都能比對。
如:

這個可以比對到的路徑有:
/cross/aaa
/cross/bbbb
不能比對的:
/corss/aaa/bbb
因為* 隻能比對到下一層路徑,如果想後面不管多少層都可以比對,配置如下:
<mvc:mapping path="/cross/**"/>
就是一顆星(*) 變成兩顆星(**)
上面表示有/cross/路徑的請求都支援跨域通路,也可以增加其它的,如下:

<mvc:mapping path="/cross/**" allowed-origins="" max-age="2500"/>
<mvc:mapping path="/domain/**"/>
請求路徑有/cross/,方法示例如下:

@RequestMapping("/cross/crossDomain")
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
(如果你覺得文章對你有幫助,歡迎捐贈,^_^,謝謝!)
今天越懶,明天要做的事越多。