users@jersey.java.net

Re: [Jersey] Communicating with Jersey from servlet filter

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 02 Dec 2008 15:47:55 +0100

Hi Rod,

On Dec 2, 2008, at 3:33 PM, Rod Fitzsimmons Frey wrote:

> I’m having a lot of trouble creating a custom realm in Glassfish,
> which I’m trying to work through on the Glassfish list.
>

The following may help you:

   http://markmail.org/message/oz3gukd2cnhsces6?q=list:net.java.dev.jersey.users+realm
   http://markmail.org/message/gplle5rtvapfyeog?q=list:net.java.dev.jersey.users+realm

But i agree this could be made a lot easier.


> To keep moving forward, I’ve implemented a servlet filter to do
> authentication.
>
> However, I’m unclear on the best way to communicate with my Resource
> classes from the servlet container. Back in the day, I’d stuff an
> object (in this case the authenticated user) into the
> HttpServletRequest using setAttribute, or if it was long lived into
> the session. Obviously restful objects don’t have a session concept
> since they’re stateless, but I’d still like to communicate with the
> resources from the filter.
>
> Am I misunderstanding a basic architectural aspect of jersey?
>

No. You can still use attributes on the HttpServletRequest if you wish
as this can be injected into resource classes with @Context.

A pattern that is useful is to create your own injectable object that
wraps around the properties set on HttpServletRequest. For example you
could do:

@Provider
public MyXYZProvider extends PerRequestTypeInjectableProvider<Context,
XYZ> {
    @Context HttpServletRequest hsr

    public abstract Injectable<T> getInjectable(ComponentContext ic,
Context a) {
        return new Injectable<XYZ>() {
            public XYZ getValue() {
                // get attributes from hsr
                return new XYZ(...);
            }
        };
    }
}

And in your resource class:

  @Context XYZ xyz;

Note that if you don't want to bind to servlet you could use a Jersey
filter and set properties on @HttpContext. The nice thing about using
an injectable provider is that such details are hidden from the
resource classes.

Paul.