0

我想允许跨源请求到我的服务器。我找到了以下过滤器代码:

public class CorsFilter implements Filter {
  // For security reasons set this regex to an appropriate value
  // example: ".*example\\.com"
  private static final String ALLOWED_DOMAINS_REGEXP = ".*";

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

    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;

    String origin = req.getHeader("Origin");

    if (origin != null && origin.matches(ALLOWED_DOMAINS_REGEXP)) {
          System.out.println("CorsFilter:: origin matches, yey");
      resp.addHeader("Access-Control-Allow-Origin", origin);

      if ("options".equalsIgnoreCase(req.getMethod())) {

        resp.setHeader("Allow", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
        if (origin != null) {
          String headers = req.getHeader("Access-Control-Request-Headers");
          String method = req.getHeader("Access-Control-Request-Method");
          resp.addHeader("Access-Control-Allow-Methods", method);
          resp.addHeader("Access-Control-Allow-Headers", headers);
          resp.setContentType("text/plain");
        }
        resp.getWriter().flush();
        return;
      }
    }

    // Fix ios6 caching post requests
    if ("post".equalsIgnoreCase(req.getMethod())) {
      resp.addHeader("Cache-Control", "no-cache");
    }

    if (filterChain != null) {
      filterChain.doFilter(req, resp);
    }
  }

  @Override public void destroy() {}
  @Override public void init(FilterConfig arg0) throws ServletException {}
}

似乎只有在首先有一个 OPTIONS 请求时它才会做任何事情。但是,就我而言,我没有看到任何 OPTIONS 请求,而只有一个 GET 请求。我错过了什么吗?解决办法是什么?

4

1 回答 1

0

从 Tomcat 7.0.41 开始,您可以通过内置过滤器控制 CORS 行为。

您几乎唯一需要做的就是在 CATALINA_HOME/conf 中编辑全局 web.xml 并添加过滤器定义:

     <!-- ================== 内置过滤器定义 ====================-->

      ...

     <过滤器>
       <filter-name>CorsFilter</filter-name>
       <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
     </过滤器>
     <过滤器映射>
       <filter-name>CorsFilter</filter-name>
       <url-pattern>/*</url-pattern>
     </filter-mapping>

    <!-- ==================== 内置过滤器映射 ====================== -->

于 2014-01-20T16:14:09.173 回答