Tuesday, 14 July 2015

How to use HttpSessionListener in Java EE

In dynamic web application user may store details in different scope. If data wants to be shared among more than one request at that time it can be stored inside "HttpSession". If we want to keep track that when HttpSession object gets created and destryoed then HttpSessionListener is the option one need to use.

HttpSession Lifecycle has below two events ,here are the main events of it:

1) session created
2) session destroyed

If we want to perform any action while session is created or destroyed then below three steps needs to be performed:

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "HttpSessionListener"
3) Run and Verify

Lets see the steps in detailed:

1) Modify web.xml (deployment descriptor) file to add listener

web.xml file will be read / looked upon by the container while loading any of the project. To inform container about "HttpSessionListener" we need to add below
lines in it:

<listener>
<listener-class>com.listener.MyHttpSessionListener</listener-class>
</listener>

2) Add a class which implements "HttpSessionListener"

Here is the code snippet for the  quick reference:

public class MyHttpSessionListener implements HttpSessionListener {

    public MyHttpSessionListener() {
    }

    public void sessionCreated(HttpSessionEvent arg0) {
    System.out.println("Session Created");
    }

    public void sessionDestroyed(HttpSessionEvent arg0) {
    System.out.println("Session Destroyed");
    }
}

As we can see there are two methods "sessionCreated" and "sessionDestroyed" which will be called at the time of HttpSession object created and destroyed respectively.

3) Run and Verify

Lets create a dummy servlet called "SessionLifecyclTest" which has below "doGet" method which creates and invalidates the HttpSession object:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.invalidate();
}

when we run the Url : "http://localhost:8080/student/SessionLifeyCycleTest" and hit enter below lines we can see inside logs:

Session Created //Line #1
Session Destroyed //Line #2

where,

Line #1 is the result of 1st line of the "doGet" method (SessionLifecycleTest)
Line #2 is the result of the 2nd line of the "doGet" method (SessionLifecyclTest)

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

No comments:

Post a Comment