使用Filter处理跨域
- 创建Filter
public class CorsFilter implements Filter {
private String allowedOrigins = "*";
private String allowedMethods = "GET, POST";
private String allowedHeaders = "*";
private String exposedHeaders = "";
private String allowCredentials = "false";
private String maxAge = "1800";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (filterConfig.getInitParameter("allowedOrigins") != null) {
allowedOrigins = filterConfig.getInitParameter("allowedOrigins");
}
if (filterConfig.getInitParameter("allowedMethods") != null) {
allowedMethods = filterConfig.getInitParameter("allowedMethods");
}
if (filterConfig.getInitParameter("allowedHeaders") != null) {
allowedHeaders = filterConfig.getInitParameter("allowedHeaders");
}
if (filterConfig.getInitParameter("exposedHeaders") != null) {
exposedHeaders = filterConfig.getInitParameter("exposedHeaders");
}
if (filterConfig.getInitParameter("allowCredentials") != null) {
allowCredentials = filterConfig.getInitParameter("allowCredentials");
}
if (filterConfig.getInitParameter("maxAge") != null) {
maxAge = filterConfig.getInitParameter("maxAge");
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", this.allowedOrigins);
response.setHeader("Access-Control-Allow-Methods", this.allowedMethods);
response.setHeader("Access-Control-Allow-Headers", this.allowedHeaders);
if (this.allowCredentials != null) {
response.setHeader("Access-Control-Allow-Credentials", this.allowCredentials);
}
if (this.exposedHeaders != null) {
response.setHeader("Access-Control-Expose-Headers", this.exposedHeaders);
}
if (this.maxAge != null) {
response.setHeader("Access-Control-Max-Age", maxAge);
}
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
if (!httpServletRequest.getMethod().equals("OPTIONS")) {
filterChain.doFilter(servletRequest, response);
}
}
@Override
public void destroy() {
}
}
- 配置Web.xml
注意 Filter 的顺序,请求应该最先到达这个Filter
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.chuchujie.mall.gold.common.web.CorsFilter</filter-class>
<init-param>
<param-name>allowedMethods</param-name>
<param-value>GET, POST, OPTIONS</param-value>
</init-param>
<init-param>
<param-name>allowedHeaders</param-name>
<param-value>token</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>