Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request

Mark Estrada picture Mark Estrada · Jun 26, 2012 · Viewed 94.9k times · Source

I find this article to be useful for non-ajax request How to handle session expiration and ViewExpiredException in JSF 2? but I can't make use of this when I am submitting using an AJAX call.

Suppose in a primefaces dialog, I am making a post request using AJAX and session has already timed out. I see my page getting stuck.

How to fix this kind of scenario such that when I post using AJAX, I could redirect him to my view expired page and then forward him to the login page similar to the solution in the link above?

JSF2/Primefaces/Glassfish

Answer

BalusC picture BalusC · Jun 26, 2012

Exceptions which are thrown during ajax requests have by default totally no feedback in the client side. Only when you run Mojarra with project stage set to Development and use <f:ajax>, then you will get a bare JavaScript alert with the exception type and message. But other than that, and in PrimeFaces, there's by default no feedback at all. You can however see the exception in the server log and in the ajax response (in the webbrowser's developer toolset's "Network" section).

You need to implement a custom ExceptionHandler which does basically the following job when there's a ViewExpiredException in the queue:

String errorPageLocation = "/WEB-INF/errorpages/expired.xhtml";
context.setViewRoot(context.getApplication().getViewHandler().createView(context, errorPageLocation));
context.getPartialViewContext().setRenderAll(true);
context.renderResponse();

Alternatively, you could use the JSF utility library OmniFaces. It has a FullAjaxExceptionHandler for exactly this purpose (source code here, showcase demo here).

See also: