Jersey 请求过滤器仅在某些 URI 上 [英] Jersey Request Filter only on certain URI

查看:16
本文介绍了Jersey 请求过滤器仅在某些 URI 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ContainerRequestFilter 对进入我的服务的请求进行一些验证.一切正常,但是有一个问题 - 每个请求都会通过过滤器,即使某些过滤器永远不会应用于它们(一个过滤器仅在 ResourceOne 上验证,另一个仅在 ResourceTwo 上验证等)

I am trying to do some validation on requests coming into my service using the ContainerRequestFilter. Everything is working fine, however there is one problem - every single request gets pass through the filters, even though some of the filters will never apply to them (one filter only validates on ResourceOne, another only on ResourceTwo etc.)

有没有办法将过滤器设置为仅在特定条件下对请求调用?

Is there a way to set a filter only to be invoked on a request under certain conditions?

虽然它不是阻碍或阻碍,但如果能够阻止这种行为就好了:)

While it is not a blocker or hindrance, it would be nice to be able to stop this kind of behaviour :)

推荐答案

我假设您使用的是 Jersey 2.x(JAX-RS 2.0 API 的实现).

I assume that You are using Jersey 2.x (implementation for JAX-RS 2.0 API).

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

You have two ways to achieve Your goal.

1.使用名称绑定:

1.1 创建带有@NameBinding 注解的自定义注解:

1.1 Create custom annotation annotated with @NameBinding:

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

1.2.使用您的注释创建过滤器:

1.2. Create filter with Your annotation:

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

1.3.并将创建的过滤器与选定的资源方法绑定:

1.3. And bind created filter with selected resource method:

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

2.使用 DynamicFeature:

2.1.创建过滤器:

public class ResourceOneFilter implements ContainerRequestFilter {
...
}

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

2.2. Implement javax.ws.rs.container.DynamicFeature interface:

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

在这种情况下:

  • 过滤器没有使用 @Provider 注释;
  • configure(...) 方法被每个资源方法调用;
  • ctx.register(filter) 将过滤器与资源方法绑定;
  • filter is not annotated with @Provider annotation;
  • configure(...) method is invoked for every resource method;
  • ctx.register(filter) binds filter with resource method;

这篇关于Jersey 请求过滤器仅在某些 URI 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆