|
Page 5 of 6
Implementation of HttpSessionListener
Okay, now, let’s go to HttpSessionListener. HttpSessionListener is mostly used for session management. Unlike ServletContextListener, HttpSessionListener is used to deal with the HttpSession object.
Session is considered created if you assign some attribute to it and similarly, it is considered to be destroyed if you have invalidated it. There is a method that you can call in the Session class to invalidate the session. Have you ever seen a web application that will ask you to re-login if you leave the site untouched for certain periods of times? It checks the time you are not active and will invalidate the session if the inactive time has reached the limit.
Albeit Listener is part of the Servlet, we can create a simple Java class and modify it to be a Listener similar to the ServletContextListener.
Now, we have an error in our class. Why? Because once we try to implement the javax.servlet.HttpSessionListener interface, we need to define a few implementation methods for it. That’s why I mentioned earlier that it is the pre-defined interfaces. This is where our job will be started. You need to add two methods for it.
- public void sessionCreated(HttpSessionEvent arg0)
- public void sessionDestroyed(HttpSessionEvent arg0)
So here is my latest SessionListener.java
public class SessionListener implements javax.servlet.http.HttpSessionListener {
public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("Session is created");
}
public void sessionDestroyed(HttpSessionEvent arg0) {
System.out.println("Session is destroyed");
}
}
|
Okay, if you add one attribute to the session, the session will be created for you and it should print out “Session is created”. Once you invalidate the session, the session should be destroyed and “Session is destroyed” will be printed out.
Now, we need to add one more entry in our web.xml.
<listener>
<listener-class>com.mycompany.listener.SessionListener</listener-class>
</listener>
One thing you need to know that this listener entry MUST be before the <servlet> entry (if any). So here is my latest web.xml looks like. Yes, Listener only needs <listener></listener>
If you follow correctly as our previous Listener, you should have something like below illustrations.
This is the latest web.xml that I had. It shows that I am having two listeners at one time.
Ok, actually we have completed our SessionListener. The only thing is that how to test it. There is one thing you can do. Create one JSP on your web application and we will assign some attributes to the sessions (adding attribute means that we are creating the Session). Create your JSP using the wizard and name it whatever you want. For my case, I would like to name it testSession.jsp.
|
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.