Tuesday, February 03, 2009

JSF Managed Bean in a Servlet Filter

" How do you get a JSF Managed Bean, with session scope, in a Servlet Filter ? "

- Two bewildered comrades

The question posed above can be reworded in a simpler way :-

" Which came first, the Chicken or the Egg ? "

- A timeless paradox

We just hit this problem of accessing a JSF managed bean from a Servlet Filter. The requirement is quite simple - Oracle Single Sign On authenticates a user, passes on useful information about the user in the request headers & this information needs be passed on downstream to a Managed Bean for furthe consumption.

However, try as much as we can, we only hit the simple NullPointerException, which quaintly informs us that we aren't getting the FacesContext to proceed further.

A bit of Googling landed us on a post on the Sun Java Forums, where one of the legends of the Java Universe - Craig McClanahan - has suggested that this might not be possible. He has eloquently described how the Servlet Filters get triggered much before the Servlets & hence, the FacesContext doesn't stand a chance of getting initialized unless the flow hits the FacesServlet.

However, on further Googling, we hit upon this curious post on the Thougths About blog that offers an amazing alternative! We tried the code posted on the blog and.... it just works !

Thanks a million to the Thougths About blog for shaving off a few precious hours off the already-harried schedule of a couple of developers !

You can also find a very good explanation about the differences between a Filter and a PhaseListener on the same Blog.

Now, it's time for a cup of coffee.....

No comments: