Pages

Thursday, January 24, 2013

JSF 2.x Tip of the Day: AJAX Redirection from @WebFilter (Filter)

I was working on an application where I needed to have it redirect to a login page when certain conditions exist in the application, e.g. session timeout, etc. A ViewExpiredException custom exception handler (available in JSF 2.0) can handle this case, but I had a need for another type of "Session" object to be monitored to determine if I should redirect based on its status. The other object was stored in the HttpSession object as an attribute so I decided to handle it with a Filter (@WebFilter).

The first thing is to determine if the request is a partial/ajax request. If it is a normal post, we can handle it with a HttpResponse.sendRedirect(String location) mechanism. If it is AJAX, we need to handle it in a completely different manner. Once I determined that the request was AJAX, I needed to be able to pass the appropriate response back to the JSF page in a format that it could understand. A great tip came from Jim Driscoll's blog: Redirecting from a JSF 2.0 Ajax Request which gave me the general syntax for what I needed to send back.

Note: This is being intercepted in a Filter so I don't have access to the FacesContext. Here is a partial code snippet of how to send the redirect. You would need to set the variable TARGET to go to the desired location.

2 comments :