一:SpringMVC4.x以下,就需要对该请求配置Filter,设置请求头可支持跨域。
1.web.xml配置
header
com.foriseland.fsoa.pay.filter.HeaderFilter
header
/*
-->
3.自定义Filter拦截请求,添加跨域请求支持
package com.foriseland.fsoa.pay.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 头部过滤器
* @author
*/
public class HeaderFilter implements Filter{
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse) res;
String originHeader = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "0");
response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("XDomainRequestAllowed","1");
response.setHeader("XDomainRequestAllowed","1");
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
二、SpringMVC4.x以上,从SpringMVC4.x开始,就增加了支持跨域访问。
1、某个方法支持跨域访问:在方法上增加@CrossOrigin注解
@RequestMapping("/crossDomain2")
@ResponseBody
@CrossOrigin
public String crossDomain2(HttpServletRequest req, HttpServletResponse res, String name){
……
……
}
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){
……
……
}