users@jersey.java.net

Re: [Jersey] Re: Filters

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 10 Feb 2009 10:50:45 +0100

Hi Fabio,

CC'ing Alex as this is related to the discussion we have been having
of the "Destroying injected context at the end of resource lifecycle"
thread.


On Feb 7, 2009, at 3:50 PM, Fabio Mancinelli wrote:

> On Fri, Feb 6, 2009 at 6:47 PM, Fabio Mancinelli
> <fabio.mancinelli_at_gmail.com> wrote:
>> Dear all,
>>
>> I am stuck with the following problem: I would like to implement a
>> "setup/cleanup" filter that, before calling any resource, must do the
>> following
>>
>> 1) Perform some initializations
>> 2) Make some environment objects available to the resource that will
>> be called after.
>> 3) Cleanup after the request has been served (no matter what, even if
>> exceptions are thrown, a bit like a finally)
>>
> I think I've found a solution to the problem, so I am sharing it
> with you.
>
> Basically I create a class that implements the ContainerRequestFilter
> and ContainerResponseFilter and setup this filter in the web.xml
>
> In the filter(ContainerRequest request) method I use the
> request.getProperties() map in order to store my environment objects.
>
> A resource willing to retrieve those object must declare a @Context
> HttpContext variable.
>
> The injected value contains a map that can be retrieved using the
> getProperties() method.
> This map will contain all the objects that I've stored in the filter
> method.
>
> That's it.
>

Yes, that is it. A technique we sometimes employ to avoid the user
having to inject HttpContext and then extract the property and cast is
to use an injectable provider to do that job. It makes the resource
class a little cleaner. Plus potentially the use of the injectable
provider means that one does not have to know upfront the environment
objects that may be utilized.

There is currently one issue i mentioned to Alex:

   Currently any exception thrown by a response filter will terminate
the response filter chain. But i am wondering this is the
   right thing to do and instead each filter should be wrapped around
exception checking. I would appreciate any advice on
   this aspect.

Paul.