我们在开发过程中,会遇到服务端是一个端口,WEB端是另一个端口的情况,这个时候ajax发起请求到服务端就会出现跨域的问题。具体情况如下:
Error:
XMLHttpRequest cannot load http://127.0.0.1:8080/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.
我们找到了一个比较好的解决办法,通过拦截器进行处理这些跨域请求问题。
Java代码:
public class VisitFilter implements Filter{
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
chain.doFilter(req, res);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
Web.Xml配置:
<!-- 具体Package中类的位置按照项目需求进行配置 -->
<filter>
<filter-name>VisitFilter</filter-name>
<filter-class>com.system.VisitFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>VisitFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>