1.web.xml 配置
<!-- 跨域问题解决 --> <filter> <filter-name>header</filter-name> <filter-class>com.foriseland.fsoa.pay.filter.HeaderFilter</filter-class> </filter> <filter-mapping> <filter-name>header</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.自定义 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 { } }
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 文件中配置映射路径
<mvc:cors> <mvc:mapping path="/cross/*"/> </mvc:cors>
如果整个项目所有方法都可以访问,则可以这样配置
<mvc:cors> <mvc:mapping path="/**"/> </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){ …… …… }