On 01/04/2012 10:11 PM, agksmehx_at_gmail.com wrote:
> In a regular Web Application, I can assign a chain of Filters to
> various paths for aspects such as Authentication, Authorization,
> Errors, Logging and more.
>
> The advantage is that I write servlets to focus on core functionality
> without worrying about infrastructure aspects. I can write orthogonal,
> cross-cutting Filters to authenticate, authorize, etc. Then I can weave
> them in web.xml. Looking at web.xml is enough to assure me that there
> are no holes in my application.
>
> Is this possible in JAX-RS or Jersey? If not, what is my best bet?
There are a few different ways that I know of to do filtering in Jersey
(not part of the JAX-RS standard). The way you register your filter
implementations varies depending on how you're hosting Jersey (as a
regular servlet configured in web.xml, inside Guice Servlet, etc).
1. You can register implementations ContainerRequestFilter and
ContainerResponseFilter. This is suitable for filtering tasks that
aren't specific to an individual JAX-RS resource. You do not get access
to information about which specific AbstractResourceMethod is invoked.
This class of filter is useful for app-wide tasks like inspecting
authentication credentials.
2. ResourceFilterFactory is a mechanism by which filtering can be
customized for each resource method. Your implementation can create
Container[Request|Response]Filter instances (via ResourceFilter) that
are specific to each AbstractMethod. AbstractMethod (and its various
subclasses) provide easy access to the java.lang.Class of the resource,
etc. This is used by
com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory to
look for JSR-250 annotations on classes or methods and to permit or
allow requests as appropriate.
3. ResourceMethodDispatchAdapter lets you wrap
ResourceMethodDispatchProvider implementations. This gives you the
opportunity to wrap the actual invocation of the resource method the way
javax.servlet.Filter lets you. It's a little more awkward to use than
servlet filters out of the box, but I didn't have any trouble building
up a little infrastructure to allow easy registration of generic servlet
filter-style classes.
InstrumentedResourceMethodDispatchAdapter in
https://github.com/codahale/metrics/tree/master/metrics-jersey/src/main/java/com/yammer/metrics/jersey
uses this approach to get timing information.
Check out the implementations of those various interfaces that come
bundled with Jersey for more ideas on how to use them.
-Marshall