在java服务器端处理CORS

问题描述 投票:0回答:1

我们有一些受保护的资源,我们需要CORS启用。这些资源可以通过get和post获取/创建。

为了处理CORS,我们已经在服务器端处理了预检选项请求。我们有一个特殊的标题要从客户端发送,这使它成为https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS的预检请求

在收到带有原始标题的选项请求时,我们使用“Access-Control-Allow-Origin”允许原点并使“Access-Control-Allow-Credentials”,“true”。

我的问题是我还需要做什么,或者可能存在浏览器不发送预检选项请求的情况?

最好的祝福,

香味

java servlets cors
1个回答
0
投票

资料来源:https://howtodoinjava.com/servlets/java-cors-filter-example/

public class CORSFilter implements Filter {

    public CORSFilter() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("CORSFilter HTTP Request: " + request.getMethod());

        // Authorize (allow) all domains to consume the content
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");

        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // pass the request along the filter chain
        chain.doFilter(request, servletResponse);
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.