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){
……
……
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章