2.12. RESTEasy Filters 和 Interceptors


JAX-RS 有两个不同的拦截概念:过滤器和拦截器。过滤器主要用于修改或处理传入和传出请求标头或响应标头。它们在请求和响应处理之前和之后执行。

2.12.1. 服务器端过滤器

在服务器端,您有两种不同类型的过滤器:Container RequestFiltersContainerResponseFilters。在调用 JAX-RS 资源方法之前,ContainerRequestFilters 运行。ContainerResponseFilters 在调用 JAX-RS 资源方法后运行。

此外,有两种类型的 ContainerRequestFilters :预匹配和后匹配。预匹配 ContainerRequestFilters@PreMatching 注释指定,并在 JAX-RS 资源方法与传入 HTTP 请求匹配之前执行。匹配后 ContainerRequestFilters@PostMatching 注释指定,并在 JAX-RS 资源方法与传入 HTTP 请求匹配后执行。

预匹配过滤器通常用于修改请求属性,以更改它与特定资源方法的匹配方式,如 strip .xml 并添加 Accept 标头。ContainerRequestFilters 可以通过调用 ContainerRequestContext.abortWith(Response) 来中止请求。例如,如果过滤器实施了自定义身份验证协议,它可能希望中止。

执行资源类方法后,JAX-RS 运行所有 ContainerResponseFilters。通过这些过滤器,您可以在清理并发送到客户端之前修改传出响应。

示例:请求过滤器

public class RoleBasedSecurityFilter implements ContainerRequestFilter {
  protected String[] rolesAllowed;
  protected boolean denyAll;
  protected boolean permitAll;

  public RoleBasedSecurityFilter(String[] rolesAllowed, boolean denyAll, boolean permitAll) {
    this.rolesAllowed = rolesAllowed;
    this.denyAll = denyAll;
    this.permitAll = permitAll;
  }

  @Override
  public void filter(ContainerRequestContext requestContext) throws IOException  {
    if (denyAll) {
       requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
       return;
    }
    if (permitAll) return;
    if (rolesAllowed != null) {
       SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class);
       if (context != null) {
          for (String role : rolesAllowed) {
             if (context.isUserInRole(role)) return;
          }
          requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
          return;
       }
    }
    return;
  }
}

示例:Response Filter

public class CacheControlFilter implements ContainerResponseFilter {
   private int maxAge;

   public CacheControlFilter(int maxAge) {
      this.maxAge = maxAge;
   }

   public void filter(ContainerRequestContext req, ContainerResponseContext res)
           throws IOException {
      if (req.getMethod().equals("GET")) {
         CacheControl cc = new CacheControl();
         cc.setMaxAge(this.maxAge);
         res.getHeaders().add("Cache-Control", cc);
      }
   }
}

Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.