跳过球衣中特定资源的请求过滤器

Skip request filter for specific resource in jersey

我正在做一个球衣项目,我正在使用令牌身份验证,我正在使用 ContainerRequestFilter 过滤所有请求并检查它是否有令牌,但请求包括登录和注册请求,但我们需要跳过这些请求.. 我怎样才能跳过登录和注册请求的过滤? jersey 有没有实现这个的机制?

谢谢

据我所知,使用原始部署描述符 (web.xml) 无法实现此类行为。

但是,如果这是一个自定义过滤器,您可以在 doFilter()方法。但是由于您使用的是第三方过滤器,这不是可行的方法,但仍然可以实现此功能:

  1. 更改您的第三方过滤器 (ContainerRequestFilter) 映射到另一个路径而不是通配符路径:

    <filter-mapping>
      <filter-name>containerRequestFilter</filter-name>
      <url-pattern>/tokenizedpaths/*</url-pattern>
    </filter-mapping>
    
  2. 声明一个新的过滤器(稍后您会看到它的样子),它将映射到一个通配符路径以过滤所有请求并被委托将请求分派给您的 containerRequestFilter 仅当请求路径与排除的路径不匹配时(我选择 register 作为示例):

    <filter>
      <filter-name>filteringFilter</filter-name>
      <filter-class>com.sample.FilteringServletFilter</filter-class>
      <init-param>
        <param-name>excludedPaths</param-name>
        <param-value>/register</param-value>
      </init-param>
    </filter>
    
  3. FilteringServletFilter 将类似于以下内容:

    public class FilteringServletFilter implements Filter {
    
      private List<String> excludedPaths = new ArrayList<String>();
    
      public void init(FilterConfig config) throws ServletException {
        // You can declare a comma separated list to hold your excluded paths
        this.excludedPaths = Arrays.asList(config.getInitParameter("excludedPaths").split(","));
      }
    
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String path = ((HttpServletRequest) request).getRequestURI();
        // If the url is one of excluded paths, then just continue with next filter
        if (this.excludedPaths.contains(path)) {
          chain.doFilter(request, response); 
          return;
        }
        // Otherwilse, forward the request to the needed filter
        else {
          request.getRequestDispatcher("/tokenizedpaths" + path).forward(request, response);
        }
      }
    
    }