2013-04-09 141 views
0

我想允許交叉來源請求到我的服務器。 我發現下面的篩選器代碼:與tomcat服務器交叉來源資源共享

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請求。我錯過了什麼?解決辦法是什麼?

回答

0

從Tomcat 7.0.41開始,您可以通過built-in filter控制CORS行爲。

差不多,你所要做的就是編輯CATALINA_HOME/conf下的全球web.xml,然後添加過濾器定義的唯一的事:

 
    <!-- ================== Built In Filter Definitions ===================== --> 

     ... 

    <filter> 
     <filter-name>CorsFilter</filter-name> 
     <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> 
    </filter> 
    <filter-mapping> 
     <filter-name>CorsFilter</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 

    <!-- ==================== Built In Filter Mappings ====================== -->