• ServletContextListener initializes the web application. It is some thing that sits in the Container to be notified of the events during the start of web application. It kicks in before any of the servlet or JSP is instantiated. ServletContextListener is instantiated after the servletContext is created and before any of the servlet or JSP is instantiated. Refer to page 178  of “Head First Servlets and JSP”
  • Useful in init parameter lookup for creating database connections. It will store database connection as an attribute of the ServletContext. All parts of the web application can access it. All this stuff is done in              public void contextInitialized(ServletContextEvent event) function of the ServletContextListener.
  • Can also perform house keeping functions such as database connection close up before the web application demises. Typically this is performed in  public void contextDestroyed(ServletContextEvent event) function of the ServletContextListener.                                                                                                                                                      Follow the following steps to listen for servletContextEvents(application is being deployed)
  • Write a listener Class that implements ServletContextListener
    public class MyServletContextListener implements ServletContextListener
  • Put that in WEB-INF/classes directory.
  • define this to the container in the deployment descriptor web.xml as shown below

  • To implement ServletContextListener, the class you define should implement two  methods. One of them is public void contextInitialized(ServletContextEvent event).This method is executed when the application is being deployed. You get ServletContext  from ServletContextEvent  using the code  event.getServletContext(); The second method is                                                                                                               public void contextDestroyed(ServletContextEvent event). This method is executed when the application is about to shutdown.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s