java过滤器不能对跨域请求无效

我开启的是调试模式。我自己的请求进来就进了过滤器(在断点处停顿)。但是前端的人发送的请求就完全没有进入过滤器(没在断点处停顿),并且获得了响应。

如果请求的路径一样,参数,请求方式一致,是应该进来的。最好确定这些。

首先你得确定是请求的你的机子吗

1:首先确认是否关闭防火墙
2:前端一般会发送两个请求,如果第一个options(试探请求)请求被拦截, 那么真正的请求不会被响应,你可以参考下下面的手动放过options请求

public class SimpleCORSFilter 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 resp = (HttpServletResponse) response;
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Headers", "Cookie, Set-Cookie, Origin, x-requested-with, Content-Type, Accept");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");

        /*将下面地址改为页面访问的地址, "*"会导致Credentials失效!!*/
        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
                **_//放过options,不做验证_**
        if (req.getHeader("Access-Control-Request-Method") != null
                && "OPTIONS".equals(req.getMethod())) {// CORS "pre-flight" request
            resp.addHeader("Access-Control-Max-Age", "7200");
            resp.setStatus(200);
            resp.getWriter().write("OK");
            return;
        }
        if (req.getRequestURI().endsWith(".html")) {
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("Pragma", "no-cache");
            resp.setDateHeader("Expires", 0);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {}

}
    <security-constraint>
        <web-resource-collection>
            <url-pattern>/*</url-pattern>
            <http-method>PUT</http-method>
            <http-method>DELETE</http-method>
            <http-method>HEAD</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
        </web-resource-collection>
        <auth-constraint>
        </auth-constraint>
    </security-constraint>

我把web.xml里面的这段代码注释掉之后跨域请求就可以正常进入拦截器。可能就是楼上说的options试探请求被拦截了所以进不了过滤器。但是为啥可以正常进入接口代码并且获得正确的返回值呢?