在网络.xml网址模式匹配器中,有没有办法排除网址?

2022-09-01 23:26:13

我写了一个过滤器,每次访问我网站上的URL时都需要调用它,除了CSS,JS和IMAGE文件。所以在我的定义中,我希望有这样的东西:

<filter-mapping>
   <filter-name>myAuthorizationFilter</filter-name>
   <url-pattern>NOT /css && NOT /js && NOT /images</url-pattern>
</filter-mapping>

有没有办法做到这一点?我能找到的唯一文档只有 /*

更新:

我最终使用了类似于Mr.J4mes提供的答案:

   private static Pattern excludeUrls = Pattern.compile("^.*/(css|js|images)/.*$", Pattern.CASE_INSENSITIVE);
   private boolean isWorthyRequest(HttpServletRequest request) {
       String url = request.getRequestURI().toString();
       Matcher m = excludeUrls.matcher(url);

       return (!m.matches());
   }

答案 1

我想你可以试试这个:

@WebFilter(filterName = "myFilter", urlPatterns = {"*.xhtml"})
public class MyFilter implements Filter {

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
      String path = ((HttpServletRequest) request).getServletPath();

      if (excludeFromFilter(path)) chain.doFilter(request, response);
      else // do something
   }

   private boolean excludeFromFilter(String path) {
      if (path.startsWith("/javax.faces.resource")) return true; // add more page to exclude here
      else return false;
   }
}

答案 2

URL 模式映射不支持排除项。这是 Servlet 规范的一个限制。您可以尝试 Mr.J4mes 发布的手动解决方法。


推荐