Manoj
Manoj

Reputation: 39

how to insert data in database before session timeouts within given time limit using java?

If I am mentioning the session timeout in descriptor page

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

Before terminating session I want to do insert operation in database. Is there any possibility for insertion. I have a thought that when user logins the page and I can use trigger to insert the data for 30 minutes. But if anyone else changes to -1 or more than 30 mins without noticing the trigger is running when user logins at that case what can I do for it?

Upvotes: 1

Views: 777

Answers (1)

icza
icza

Reputation: 417412

The remaining time for a session timeout changes every time the client makes interaction, so timing this for 30 minutes is a wrong solution.

Instead use an HttpSessionListener. A registered HttpSessionListener is called every time an HTTP session is created or destoryed (invalidated). This does not depend on the configured session timeout. The sessionDestroyed() method is always called right before a session is invalidated and discarded.

public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {}

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // Here session is destoryed.
        // You can insert data to your database here.
        // You can access the session like this:
        HttpSession sess = se.getSession();
    }
}

Here is how you can register your HttpSessionListener it in your web.xml:

<web-app>
    <listener>
        <listener-class>com.dummy.MySessionListener</listener-class>
    </listener>
</web-app>

Upvotes: 3

Related Questions