users@jersey.java.net

[Jersey] Re: Equivalent of a Servlet Filter for Jersey / JAX-RS / REST resources?

From: Marshall Pierce <marshall_at_mpierce.org>
Date: Fri, 06 Jan 2012 02:07:53 -0800

On 01/05/2012 03:13 PM, agksmehx_at_gmail.com wrote:
> Thank you Marshall and Tatu for your excellent responses! :-)
>
> I had an additional idea last night, which seems to have the benefit of
> being JAX-RS standard:
>
> The constructor for a Resource is ordinarily invoked on a per-request
> basis prior to any method that handles a request for it, yielding way
> to hook in-bound filter logic at a coarser granularity than a method
> (but finer than a urlPatterns specification).
>
> When a Resource constructor is not invoked on a per-request basis, it
> is because a method of another Resource is responsible for its
> lifecycle, and the constructor for that Resource is invoked on a
> per-request basis. Also, in this case the method itself which is
> managing the lifecycle for the Resource is itself another hook for
> filter logic (both in-bound and out-bound) at a granularity coarser
> than a method but finer than a urlPatterns specification.
>
> Any opinion on this approach?

It's not necessarily the case that a resource constructor not being
invoked on a per-request basis is a sign of a subresource locator or
other atypical lifecycle. You may wish for performance reasons to have a
singleton instance of a resource that is re-used for every request.

Using the constructor as a means of applying filtering logic seems
somewhat awkward, and it's not where I would expect to find filters.
Also, it looks like you can't throw WebApplicationException from a
resource class constructor as a way to reject a request; it just ends up
as a 500. (This is using Guice; not sure about what happens when using
Jersey's IoC.)

Seems to me that your options for class-wide filtering are either to
have some boilerplate at the top of every resource method or to annotate
the class and use a ResourceFilterFactory that looks for classes with
that annotation.