泽西请求仅对特定URI进行过滤

我正在尝试使用ContainerRequestFilter对进入我服务的请求进行一些validation。 一切都运行正常,但是有一个问题 – 每个请求都会通过filter,即使某些filter永远不会应用于它们(一个filter只在ResourceOne上validation,另一个只在ResourceTwo等上validation)

有没有办法在某些条件下设置仅在请求上调用filter?

虽然它不是阻碍或阻碍,但能够阻止这种行为会很好:)

我假设你正在使用Jersey 2.x(JAX-RS 2.0 API的实现)。

您有两种方法可以实现您的目标。

1.使用名称绑定:


1.1创建使用@NameBinding注释的自定义注释:

 @NameBinding @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationForResourceOne {} 

1.2。 使用您的注释创建filter:

 @Provider @AnnotationForResourceOne public class ResourceOneFilter implements ContainerRequestFilter { ... } 

1.3。 并使用所选资源方法绑定创建的filter:

 @Path("/resources") public class Resources { @GET @Path("/resourceOne") @AnnotationForResourceOne public String getResourceOne() {...} } 

2.使用DynamicFeature:


2.1。 创建filter:

 public class ResourceOneFilter implements ContainerRequestFilter { ... } 

2.2。 实现javax.ws.rs.container.DynamicFeature接口:

 @Provider public class MaxAgeFeature implements DynamicFeature { public void configure(ResourceInfo ri, FeatureContext ctx) { if(resourceShouldBeFiltered(ri)){ ResourceOneFilter filter = new ResourceOneFilter(); ctx.register(filter); } } } 

在这种情况下:

  • filter未使用@Provider注释进行注释;
  • 为每个资源方法调用configure(...)方法;
  • ctx.register(filter)用资源方法绑定filter;

当我们使用@NameBinding我们需要从Filter中删除@PreMatching注释。 @PreMatching导致所有请求都通过filter。

@PreMatching不能与@NameBinding一起使用,因为在预匹配阶段尚不知道资源类/方法。 我通过从filter中删除@PreMatching并使用绑定优先级来解决此问题。 请参阅ResourceConfig.register(Object component, int bindingPriority)

在资源获得更高优先级之前要执行的filter。