Reputation: 185
I have developed a web application. In which i want to add logout functionality. For this i used HttpSessionListener, but not working as i wanted.
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
public class GetActiveSessions implements HttpSessionListener {
private static int activeSessions = 0;
public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
System.out.println("+ 1 session");
}
public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
System.out.println("- 1 session");
}
public static int getActiveSessions() {
System.out.println(activeSessions);
return activeSessions;
}
}
I marked user logout in sessionDestroyed() method(by updating Database).
If session is timeout then container calls the sessionDestroyed() method and i update the Database but when i explicitly call session.invalidate() (when user click on logout link)values are unbind from session object but container does not call sessionDestroyed() method so not able to update database.
and also need to logout user when user closes browser window.
There are three chances from where user can be marked as logout. 1. Session timeout by container. 2. User clicks on Logout link 3 User close the browser window.
Please give your valuable idea on the same.
Upvotes: 0
Views: 1295
Reputation: 1569
A work around for your problem would be using HttpSessionBindingListener whenever values gets unbind update the database.
When user closes the browser, onunload event gets triggered and You can call the respective servlet to log out user(Update the database) from logoutUser() javascript function.
< script>
function logoutUser()
{
// Call logout servlet
}
< / script >
< / head >
< body onunload="logoutUser()" >
.....
One problem with onunload is It gets triggered even when you refresh the page.
Upvotes: 1