How to handle session expiration and ViewExpiredException in JSF 2?
Asked Answered
G

1

48

Consider the following scenario. I am clicking the submit button of a JSF form, after the session has timed out(expired). The browser displays some exception message:

ViewExpiredException: view context could not be restored

What I want to do is, to automatically redirect to the homepage of the website after the session has expired. What is the mechanism to do this? Any help would be much appreciated.

Gabriellegabrielli answered 14/2, 2011 at 13:11 Comment(0)
C
92

To handle the exception whenever the user invokes a synchronous POST request on a page while the HTTP session has been expired and the JSF view state saving method is set to server, add an <error-page> to the web.xml which catches the JSF ViewExpiredException and shows the home page.

<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/home.xhtml</location>
</error-page>

To handle the exception on asynchronous (ajax) requests as well, you need to implement a custom ExceptionHandler as answered in Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request

See also:

Calmative answered 14/2, 2011 at 13:44 Comment(5)
Thank you @Calmative I added entry to the web.xml file like this <error-page> <exception-type>javax.faces.application.ViewExpiredException</exception-type> <location>/index.xhtml</location> </error-page>Still i get the exception from the glassfish server. HTTP Status 500 - **type** Exception report **message** **description** The server encountered an internal error () that prevented it from fulfilling this request. **exception** javax.faces.application.ViewExpiredException: viewId:/home.xhtml - View /home.xhtml could not be restored any suggestion pls?Gabriellegabrielli
No @Calmative I have no other error-page in web.xml file. I have configured both the welcome-file and the error-page as same.(index.xhtml). would that be a problem? shall i ask this as a seperate question to post more information regarding this?Gabriellegabrielli
Hi BalusC, there is a slight problem. It should be <location>/faces/home.xhtml</location>. Without the "/faces", the web container will just load the XHTML file return its source, completely bypassing JSF. At least that's the behavior in JBoss 7.Martyry
@RajV: apparently your webapp has the FacesServlet mapped on /faces/* instead of *.xhtml for some reason. Just change that accordingly to get rid of the ugly additional /faces path. This minor configuration issue is completely unrelated to the concrete problem as been asked here.Calmative
The use of the content attribute in the meta tag is a simple and elegant solution to a common problem.Pappas

© 2022 - 2024 — McMap. All rights reserved.