I want to display in a that the session has expired.
I found many methods to handle session expiration like Session timeout and ViewExpiredExcep
The code posted by @uı6ʎɹnɯ lǝıuɐp i's very useful, but i will add some observations:
@Jonathan L sugests replace processTimer = setTimeout("timedCount()", 1000) to setInterval("timedCount()", 1000). I think makes sense, but need some
modifications:
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
processTimer = setInterval("timedCount()", 1000);
}
}
function stopCount() {
clearInterval(processTimer);
timer_is_on = 0;
keepAlive();
}
The method timedCount() can be changed to:
function timedCount() {
txtCountDown.innerHTML = countTimer;
if (countTimer > 0) {
countTimer = countTimer - 1;
} else {
clearInterval(processTimer);
doLogout();
}
}
And you need add under the keepAlive remoteCommand something like this:
Inside Managed Bean:
public void logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
validUser = false;
loggedUser = false;
redirectToPage("/login.xhtml");
}
private void redirectToPage(String page) {
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
context.redirect(context.getRequestContextPath() + page);
}
Remember the atribute
name="doLogout"ofp:remoteCommandis converted in a javascript function that you can call anywhere. It's perfect to iterate the view with managed bean.This approach will prevent your system stacks the ViewExpiredException.
Some people doesn't understand the keepAlive concept, but it's very easy, just add a simple function inside your managed bean. Example keepSessionAlive action:
public void keepSessionAlive () {
System.out.println(">>> Session is alive... ");
}
Remember the
p:remoteCommandnamedkeepAliveis a javascript function calledkeepAlive()and that call an actionkeepSessionAliveinside your managed bean.This action signs you are not idle.
The session.maxInactiveInterval of idleMonitor references of web.xml
I recommend put session monitor to execute 5 seconds before finish the session to prevent run
doLogout()after session end and get the ViewExpiredException.
The first line of javascript code is var TIME = 120; // in seconds, this represents the time to finalize the session. The original code # {session.maxInactiveInterval * 1000 - 125000} will use session-timeout mutiplicated by 1.000 (because it's miliseconds) and subtract 125.000 that represents 125 seconds, 5 seconds less than counter, therefore doesn't need changes.