Techieexchange’s Techblog

JSF Session Expired Timeout Solution

Posted on: February 21, 2008

With JSF, a clean Session expiry or timeout is not easy to implement. So, I would like to post a solution that you can integrate it as out-of-box with your JSF applications.

Here is a better version of code with syntax highlight:

http://techieexchange.blogspot.com/2008/02/jsf-session-expiry-timeout-solution.html

Step 1:

/**
* When the user session timedout, ({@link #sessionDestroyed(HttpSessionEvent)}) method will be invoked.

* This method will make necessary cleanups (logging out user, updating db and audit logs, etc…)

* As a result; after this method, we will be in a clear and stable state. So nothing left to think about

* because session expired, user can do nothing after this point.
*

* Thanks to hturksoy 

*
*/




public class MySessionListener implements HttpSessionListener {

public MySessionListener() {

}
public void sessionCreated(HttpSessionEvent event) {

System.out.println(“Current Session created : “ + event.getSession().getId() + ” at “+ new Date());

}
public void sessionDestroyed(HttpSessionEvent event) {

// get the destroying session…

HttpSession session = event.getSession();
System.out.println(“Current Session destroyed :” + session.getId() + ” Logging out user…”);

/*

* nobody can reach user data after this point because session is invalidated already.
* So, get the user data from session and save its logout information
* before losing it.
* User’s redirection to the timeout page will be handled by the SessionTimeoutFilter.
*/





// Only if needed

try {

prepareLogoutInfoAndLogoutActiveUser(session);
} catch(Exception e) {

System.out.println(“Error while logging out at session destroyed : “ + e.getMessage());

}
}
/**

* Clean your logout operations.
*/

public void prepareLogoutInfoAndLogoutActiveUser(HttpSession httpSession) {

// Only if needed

}
}

Step 2:

/**



*When the session destroyed, MySessionListener will do necessary logout operations.

* Later, at the first request of client, this filter will be fired and redirect

* the user to the appropriate timeout page if the session is not valid.

* Thanks to hturksoy

*

*/



public class SessionTimeoutFilter implements Filter {

 // This should be your default Home or Login page
// “login.seam” if you use Jboss Seam otherwise “login.jsf” / “login.xhtml” or whatever
private String timeoutPage = “login.seam”;

public void init(FilterConfig filterConfig) throws ServletException {

}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,

ServletException {
if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {

HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
// is session expire control required for this request?

if (isSessionControlRequiredForThisResource(httpServletRequest)) {

// is session invalid?


if (isSessionInvalid(httpServletRequest)) {

String timeoutUrl = httpServletRequest.getContextPath() + “/” + getTimeoutPage();

System.out.println(“Session is invalid! redirecting to timeoutpage : “ + timeoutUrl);

httpServletResponse.sendRedirect(timeoutUrl);
return;

}
}
}
filterChain.doFilter(request, response);
}
/*

* session shouldn’t be checked for some pages. For example: for timeout page..



* Since we’re redirecting to timeout page from this filter,

* if we don’t disable session control for it, filter will again redirect to it

* and this will be result with an infinite loop…

*/

private boolean isSessionControlRequiredForThisResource(HttpServletRequest httpServletRequest) {

String requestPath = httpServletRequest.getRequestURI();
boolean controlRequired = !StringUtils.contains(requestPath, getTimeoutPage());

return controlRequired;

}
private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {

boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null)

&& !httpServletRequest.isRequestedSessionIdValid();
return sessionInValid;

}
public void destroy() {

}
public String getTimeoutPage() {

return timeoutPage;

}
public void setTimeoutPage(String timeoutPage) {

this.timeoutPage = timeoutPage;

}
}

Step 3:

Web.xml<listener>

<listener-class>

com.fpc.carconfig.session.MySessionListener
</listener-class>

</listener>

<filter>

<filter-name>SessionTimeoutFilter</filter-name>



<filter-class>

com.fpc.carconfig.session.SessionTimeoutFilter
</filter-class>
</filter>

<filter-mapping>

<filter-name>SessionTimeoutFilter</filter-name>

<url-pattern>*.seam</url-pattern> // Remember to use your correct URL pattern
</filter-mapping>Thats it.
To check whether this solution works:
Change session timeout to 1 minute in web.xml like this:

<session-config>

<session-timeout>1</session-timeout>


</session-config>

Feel free to share your comments.

16 Responses to "JSF Session Expired Timeout Solution"

Hi, thank you very much for you article!
But happen question.
Please cane you add StringUtils class to this article because in
antlr.StringUtils i no found contains() method and
please can you describe isSessionControlRequiredForThisResource() more detail

I think he is using stringutils from apache commons not from antlr.

Hi,
Q: antlr.StringUtils
A: StringUtils from Apache Commons Lang (http://commons.apache.org/downloads/download_lang.cgi), not from ANTLR

Q: isSessionControlRequiredForThisResource
A: See JavaDoc-
Session shouldn’t be checked for some pages. For example: for timeout page.. Since we’re redirecting to timeout page from this filter, if we don’t disable session control for it, filter will again redirect to it and this will be result with an infinite loop…

Here is a better version of code with syntax highlight:

http://techieexchange.blogspot.com/2008/02/jsf-session-expiry-timeout-solution.html

Cheers

Great Article! I have a question though.
Is there any chance that once the timeout expires, the application redirects the user to the timeout page without waiting for the user to make another move?
Thanks!

I tested with that, it run fine, but there is a problem.

It run twice, anyone have had the same problem same me

StringUtils() not workig for me… i am using ibm/rad
i went url which u posted to get it done….

but can you tel me wat and where i download sources or binary and all those and how do i integrate to my IDE…
should i use or integrate jars like thing(adding Externa jars)
help me
thanks

Hi prem,
You can download Apache Commons Lang from here
http://commons.apache.org/downloads/download_lang.cgi

For some reason, I don’t see control going in to Filter any time even after giving a URL pattern of *.*

Is there any thing I am missing?

some reason, I don’t see control going in to Filter any time even after giving a URL pattern of *.*

Is there any thing I am missing?

I am using Struts and I see the control going in to init() method of Filter but it never got in to doFilter() method. Can someone help me?

Nice solution, but how to use the resource bundle inside the SessionTimeoutFilter

I am having in login page

and adding error message as follows in the backing bean.
————————————————————————————
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage(severity, summary, detail);
facesContext.addMessage(clientId, message);
————————————————————————————

The error is NullPointerException, while adding messages.

you cant use ‘FacesContext.getCurrentInstance()’ in the filte b/c there is no faces context -> FacesContext.getCurrentInstance() returns ‘null’
so thats why you get the nullpointer if accessing facesContext.someThing

Hi.

Anybody knows how to add the browser close button, so I can invalidate my session when the users clicks on this button.

thanks

what about redirecting if an ajax / jquery request is used?
your way works fine if you dont have an ajax request. otherwise the ‘httpServletResponse.sendRedirect(timeoutUrl);’ is fired but swallowed by the browser using jsf 1.2 (for jsf 2.0 there are other solutions)

Hi your solution helped me a lot. but i have a problem like when the user clicks the logout button i am invalidating the session. so it automatically going to the sessionexpiry page. how to differentiate this.

Hi all,
I need to intimate user before 2 min of session expiry. and i have to provide option for further extending session. Please help to do this.

Leave a reply to Gopi Cancel reply