上次给一个网站写网站 前后端分离 最后跪在ajax跨域上面了 自己在网上找了个方法 亲试可用 记录一下
写一个类 继承HandlerInterceptorAdapter
package com.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class CommonInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); response.setHeader("Access-Control-Allow-Credentials", "true"); // 是否允许浏览器携带用户身份信息(cookie) return true; } }
然后在xml里面配置一下路径
<mvc:interceptors> <!--过滤所有请求,处理跨域请求问题 --> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.util.CommonInterceptor" /> </mvc:interceptor> </mvc:interceptors>
这样就可以了 不过有篇博客说针对简单跨域没问题。但是针对post+json请求却失败,提示跨域失败。所以下面记录一下他的解决方式
建立一个类 继承 OncePerRequestFilter
public class CrossFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { // CORS "pre-flight" request response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1800");//30 min } filterChain.doFilter(request, response); } }
web.xml里面设置一下
<filter> <filter-name>cors</filter-name> <filter-class>cn.***.filter.CrossFilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
然后就可以了 上述方式为spring3.0版本 如果是4.0版本可以用下面方式(无测)
xml里面配置
<mvc:cors> <mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800" allowed-methods="GET,POST,OPTIONS"/> </mvc:cors>
部分引用 飞昂之雪 的博客 http://www.cnblogs.com/asfeixue/p/4363372.html