解决cors跨域的filter

时间:2023-11-16 08:38:20
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered; import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* desc:
*
* @author:
* creat_date: 2018/1/4
* creat_time: 17:33
**/
@Order(Ordered.LOWEST_PRECEDENCE - 1)
@WebFilter(filterName = "headersCORSFilter", urlPatterns = "/*")
public class HeadersCorsFilter implements Filter, Ordered {
private static final Logger logger = LoggerFactory.getLogger(HeadersCorsFilter.class); private int order = Ordered.LOWEST_PRECEDENCE - 1; @Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub } @Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;
httpResp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
httpResp.setHeader("Access-Control-Allow-Origin", "*");
httpResp.setHeader("Access-Control-Allow-Credentials", "true");
httpResp.setHeader("Access-Control-Max-Age", "3600");
httpResp.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin," +
"Access-Control-Request-Method,Access-Control-Request-Headers,userID,Authentication,authentication,content-type"); chain.doFilter(request, response);
} @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public int getOrder() {
return order;
}
}