Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Delete data from Database upon closing the browser

When a user logs in to my web app, I create a session:

session.setAttribute("SessionNumber","100");

And his username is added to a table named ONLINE_USERS. Other Online users will be able to see him, they see all online users

When the user clicks on the log out button, I delete that row from the table, then I delete the session using:

session.invalidate();

But let's say the user existed the browser, his session will be gone, but the row will stay in the database as an online user, how to avoid this?

I'm using JSP-Servlets on Netbeans.

like image 863
Ali Bassam Avatar asked Feb 19 '23 07:02

Ali Bassam


1 Answers

You can enable a custom HttpSessionListener to delete the table row upon session invalidation.

public class YourHttpSessionListener implements HttpSessionListener {       
   public void sessionCreated(HttpSessionEvent event) {
   //put row in the database
   }

   public void sessionDestroyed(HttpSessionEvent event) {
     //delete the row from database     
   }
}

Declare the listener in your web.xml:

<listener>
    <listener-class>YourHttpSessionListener</listener-class>
</listener>

Note that there will be a delay between the moment the user exits the browser and his session expires on the server. But session expiration time is configurable. You should find a suitable expiration timeout: not too long so you don't display for too much offline users as online, but not too short to allow connected users an idle period.

I think this is a good trade off for a chat application developed with basic servlet and jsp technology.

like image 110
dcernahoschi Avatar answered Feb 25 '23 10:02

dcernahoschi