最近公司做了外部H5放在另外一个服务器上,要实现跨域请求本服务器上的代码
于是需要做跨域处理
1.全局过滤器
所有接口都会先经过过滤器
package com.Filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author xsx
*/
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//TODO Auto-generated method stub
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "*");//允许所有的访问
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许的请求方式
res.setHeader("Access-Control-Max-Age", "0");
res.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");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("XDomainRequestAllowed","1");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
2.web.xml中配置过滤器
放在所有配置的前面
<!-- 设置跨域访问-->
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.bayan.keke.Filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>