public class CrossDomainFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;
// 环境部署时 nginx中已经设置了 Access-Control-Allow-Origin 就不用加了
if (rep.getHeader("Access-Control-Allow-Origin") == null) {
rep.setHeader("Access-Control-Allow-Origin", "*");
}
rep.setHeader("Access-Control-Allow-Methods", "GET,POST");
// 如果请求为OPTIONS,那说明是浏览器对服务器的查询
String method = req.getMethod();
if ("OPTIONS".equals(method) || "options".equals(method)) {
return;
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;
// 环境部署时 nginx中已经设置了 Access-Control-Allow-Origin 就不用加了
if (rep.getHeader("Access-Control-Allow-Origin") == null) {
rep.setHeader("Access-Control-Allow-Origin", "*");
}
rep.setHeader("Access-Control-Allow-Methods", "GET,POST");
// 如果请求为OPTIONS,那说明是浏览器对服务器的查询
String method = req.getMethod();
if ("OPTIONS".equals(method) || "options".equals(method)) {
return;
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
web.xml中配置
<filter>
<filter-name>CrossDomainFilter</filter-name>
<filter-class>com.codyy.slr.filter.CrossDomainFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CrossDomainFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>