有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java手动执行CORS

我正在调试我的web应用程序, 我有一个邮件请求。(使用ajax,xhrFields:{withCredentials:true})。数据类型是“application/json”,我的服务器是tomcat,我手动将“accesscontrolalloworigin”头设置为“http://localhost:8080

其他标题: 回答addHeader(“访问控制允许凭据”、“true”); 回答addHeader(“访问控制允许标头”、“x-request-verification-token”)

我不能让它工作。这是我得到的错误:

已阻止跨源请求:同源策略不允许读取位于http://localhost:8080/MysServlet的远程资源。(原因:CORS标头“访问控制允许来源”与“http://localhost:8080”不匹配。)

谢谢你


共 (1) 个答案

  1. # 1 楼答案

    如果希望配置适用于所有请求,请在web.xml中添加以下筛选器:

    <filter>
        <filter-name>originfilter</filter-name>
        <filter-class>it.damore.web.ApiOriginFilter</filter-class>
    </filter>
    
    <filter-mapping> 
        <filter-name>originfilter</filter-name>
        <url-pattern>/*</url-pattern> 
    </filter-mapping> 
    

    这是ApiOriginFilter类:

     public class ApiOriginFilter implements javax.servlet.Filter {
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
            res.addHeader("Access-Control-Allow-Headers", "Content-Type");
            chain.doFilter(request, response);
        }
    
        public void destroy() {
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    }