22

I'm trying to implement a ContainerRequestFilter that does custom validation of a request's parameters. I need to look up the resource method that will be matched to the URI so that I can scrape custom annotations from the method's parameters.

Based on this answer I should be able to inject ExtendedUriInfo and then use it to match the method:

public final class MyRequestFilter implements ContainerRequestFilter {

    @Context private ExtendedUriInfo uriInfo;

    @Override
    public ContainerRequest filter(ContainerRequest containerRequest) {

        System.out.println(uriInfo.getMatchedMethod());

        return containerRequest;
    }
}

But getMatchedMethod apparently returns null, all the way up until the method is actually invoked (at which point it's too late for me to do validation).

How can I retrieve the Method that will be matched to a given URI, before the resource method is invoked?


For those interested, I'm trying to roll my own required parameter validation, as described in JERSEY-351.

4

4 回答 4

21

实际上,您应该尝试注入ResourceInfo自定义请求过滤器。我已经用 RESTEasy 试过了,它在那里工作。优点是您针对 JSR 接口而不是 Jersey 实现进行编码。

public class MyFilter implements ContainerRequestFilter
{
    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext)
            throws IOException
    {
        Method theMethod = resourceInfo.getResourceMethod();
        return;
    }
}
于 2014-07-18T10:36:47.203 回答
15

I figured out how to solve my problem using only Jersey. There's apparently no way to match a request's URI to the method that will be matched before that method is invoked, at least in Jersey 1.x. However, I was able to use a ResourceFilterFactory to create a ResourceFilter for each individual resource method - that way these filters can know about the destination method ahead of time.

Here's my solution, including the validation for required query params (uses Guava and JSR 305):

public final class ValidationFilterFactory implements ResourceFilterFactory {

    @Override
    public List<ResourceFilter> create(AbstractMethod abstractMethod) {

        //keep track of required query param names
        final ImmutableSet.Builder<String> requiredQueryParamsBuilder =
                ImmutableSet.builder();

        //get the list of params from the resource method
        final ImmutableList<Parameter> params =
                Invokable.from(abstractMethod.getMethod()).getParameters();

        for (Parameter param : params) {
            //if the param isn't marked as @Nullable,
            if (!param.isAnnotationPresent(Nullable.class)) {
                //try getting the @QueryParam value
                @Nullable final QueryParam queryParam =
                        param.getAnnotation(QueryParam.class);
                //if it's present, add its value to the set
                if (queryParam != null) {
                    requiredQueryParamsBuilder.add(queryParam.value());
                }
            }
        }

        //return the new validation filter for this resource method
        return Collections.<ResourceFilter>singletonList(
                new ValidationFilter(requiredQueryParamsBuilder.build())
        );
    }

    private static final class ValidationFilter implements ResourceFilter {

        final ImmutableSet<String> requiredQueryParams;

        private ValidationFilter(ImmutableSet<String> requiredQueryParams) {
            this.requiredQueryParams = requiredQueryParams;
        }

        @Override
        public ContainerRequestFilter getRequestFilter() {
            return new ContainerRequestFilter() {
                @Override
                public ContainerRequest filter(ContainerRequest request) {

                    final Collection<String> missingRequiredParams =
                            Sets.difference(
                                    requiredQueryParams,
                                    request.getQueryParameters().keySet()
                            );

                    if (!missingRequiredParams.isEmpty()) {

                        final String message =
                                "Required query params missing: " +
                                Joiner.on(", ").join(missingRequiredParams);

                        final Response response = Response
                                .status(Status.BAD_REQUEST)
                                .entity(message)
                                .build();

                        throw new WebApplicationException(response);
                    }

                    return request;
                }
            };
        }

        @Override
        public ContainerResponseFilter getResponseFilter() {
            return null;
        }
    }
}

And the ResourceFilterFactory is registered with Jersey as an init param of the servlet in web.xml:

<init-param>
    <param-name>com.sun.jersey.spi.container.ResourceFilters</param-name>
    <param-value>my.package.name.ValidationFilterFactory</param-value>
</init-param>

At startup, ValidationFilterFactory.create gets called for each resource method detected by Jersey.

Credit goes to this post for getting me on the right track: How can I get resource annotations in a Jersey ContainerResponseFilter

于 2013-05-08T17:29:33.653 回答
3

我知道您正在寻找仅适用于泽西岛的解决方案,但这里有一种 Guice 方法可以让事情正常进行:

public class Config extends GuiceServletContextListener {

  @Override
  protected Injector getInjector() {
    return Guice.createInjector(
        new JerseyServletModule() {
          @Override
          protected void configureServlets() {
            bindInterceptor(Matchers.inSubpackage("org.example"), Matchers.any(), new ValidationInterceptor());
            bind(Service.class);

            Map<String, String> params = Maps.newHashMap();
            params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "org.example");
            serve("/*").with(GuiceContainer.class, params);
          }
        });
  }

  public static class ValidationInterceptor implements MethodInterceptor {    
    public Object invoke(MethodInvocation method) throws Throwable {
      System.out.println("Validating: " + method.getMethod());
      return method.proceed();
    }
  }

}
@Path("/")
public class Service {

  @GET
  @Path("service")
  @Produces({MediaType.TEXT_PLAIN})
  public String service(@QueryParam("name") String name) {
    return "Service " + name;
  }

}

编辑:性能比较:

public class AopPerformanceTest {

  @Test
  public void testAopPerformance() {
    Service service = Guice.createInjector(
        new AbstractModule() {
          @Override
          protected void configure() { bindInterceptor(Matchers.inSubpackage("org.example"), Matchers.any(), new ValidationInterceptor()); }
        }).getInstance(Service.class);
    System.out.println("Total time with AOP: " + timeService(service) + "ns");
  }

  @Test
  public void testNonAopPerformance() {
    System.out.println("Total time without AOP: " + timeService(new Service()) + "ns");
  }

  public long timeService(Service service) {
    long sum = 0L;
    long iterations = 1000000L;
    for (int i = 0; i < iterations; i++) {
      long start = System.nanoTime();
      service.service(null);
      sum += (System.nanoTime() - start);
    }
    return sum / iterations;
  }

}
于 2013-05-04T01:48:14.660 回答
0

在 resteasy-jaxrs-3.0.5 中,您可以ResourceMethodInvoker从 a 中检索表示匹配资源方法的 ContainerRequestContext.getProperty()a ContainerRequestFilter

   import org.jboss.resteasy.core.ResourceMethodInvoker;

   public class MyRequestFilter implements ContainerRequestFilter
   {
       public void filter(ContainerRequestContext request) throws IOException
       {
            String propName = "org.jboss.resteasy.core.ResourceMethodInvoker";
            ResourceMethodInvoker invoker = (ResourceMethodInvoker)request.getProperty();
            invoker.getMethod().getParameterTypes()....
       }
   }
于 2014-04-30T19:50:14.237 回答