Saturday, February 25, 2012

Listeners

Sometimes your web application needs to know about lifecycle events - such as when a new session starts, a session expires, an attribute is added to the context, etc.

You can write a Listener class and register it in web.xml.

In your /src/org/confucius folder, create a class SessionTimeoutListener.java, like this:
 package org.confucius;  

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class SessionTimeoutListener implements HttpSessionListener {
private Logger logger;

public SessionTimeoutListener(){
PropertyConfigurator.configure("log4j.properties");
logger = Logger.getLogger(HelloWorld.class);
}

public void sessionCreated(HttpSessionEvent event) {
logger.info("Session created.");
}

public void sessionDestroyed(HttpSessionEvent event) {
logger.info("Session destroyed.");
}

}

This is a Listener class - it implements the HttpSessionListener interface.
It is notified whenever a session is created and destroyed.

Note that we have used log4j to write logs - this post explains how to use log4j.

Register this class in your web.xml, like this:
 <web-app>   
<listener>
<listener-class>org.confucius.SessionTimeoutListener</listener-class>
</listener>

<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>


That's it.
Note that we are specifying a session timeout of 1 minute.

In your /web-content/jsp folder, create a file home.jsp, like this:
 <html>  
<body>
<p>Welcome to Confucius</p>
</body>
</html>

Build and deploy HelloWorld.war, then point your nrowser to:
http://localhost:8080/HelloWorld/jsp/home.jsp

This will start a new session.

If you open your HelloWorld.log file (in <tomcat_install_dir>/logs), you will see a log for when the session was created.

No comments: