引起跨域的原因有很多
我们使用springmvc作为后端服务,使用angularjs作为前端,由于两个程序运行时的端口号不同,前端在接收数据时就会引起跨域。
当然我们可以在浏览器安装跨域插件,但是当项目部署的时候,我们不能让每个用户都去装插件。
下面是跨域的一种结局办法。
自定义一个Filter
package com.lishiqi.ssm.Filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by HASEE on 2017-2-21.
*/
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
}
在web.xml中添加配置
<filter>
<filter-name>cors</filter-name>
<filter-class>com.app.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但是以上只能解决 get delete请求,post+json的请求还是不行。
看解决问题的升级版。
public class CrossInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.addHeader("Access-Control-Allow-Origin","*");
response.addHeader("Access-Control-Allow-Methods","*");
response.addHeader("Access-Control-Max-Age","100");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Allow-Credentials","false");
return super.preHandle(request, response, handler);
}
}
spring-mvc配置文件中配置如下:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**/*"/>
<bean class="cn.***.filter.CrossInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
在定义一个filter
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>
此时,option请求被CrossFilter过滤器接入并赋予跨域响应头,同时也进入FrameworkServlet中的doOption方法。查看浏览器控制台,发现option请求返回支持跨域信息,后续的post请求进入controller。