Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Wednesday, May 30, 2012

What is Listener?

Listener is something sitting there and wait for specified event happened, then “hijack” the event and run it’s own event.

Let’s say…

You want to initialize the database connection pool before the web application is start, is there a “main()” method in whole web application?

Solution

The “ServletContextListener” is what you want. It will make your code run before the web application is start.


ServletContextListener is a interface which contains two methods:
  • public void contextInitialized(ServletContextEvent event)
  • public void contextDestroyed(ServletContextEvent event) 
1) Create a class and implement the ServletContextListener interface
package com.mkyong;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class AppServletContextListener implements ServletContextListener{
 
 @Override
 public void contextDestroyed(ServletContextEvent arg0) {
  System.out.println("ServletContextListener destroyed");
 }
 
 @Override
 public void contextInitialized(ServletContextEvent arg0) {
  System.out.println("ServletContextListener started"); 
 }
}
2) Put it in deployment descriptor
<web-app ...>
 <listener>
  <listener-class>com.mkyong.AppServletContextListener</listener-class>
 </listener>
</web-app>