Home » ServletContextEvent and ServletContextListener in Servlet

ServletContextEvent and ServletContextListener in Servlet

by Online Tutorials Library

ServletContextEvent and ServletContextListener

The ServletContextEvent is notified when web application is deployed on the server.

If you want to perform some action at the time of deploying the web application such as creating database connection, creating all the tables of the project etc, you need to implement ServletContextListener interface and provide the implementation of its methods.


Constructor of ServletContextEvent class

There is only one constructor defined in the ServletContextEvent class. The web container creates the instance of ServletContextEvent after the ServletContext instance.

  1. ServletContextEvent(ServletContext e)

Method of ServletContextEvent class

There is only one method defined in the ServletContextEvent class:

  1. public ServletContext getServletContext(): returns the instance of ServletContext.

Methods of ServletContextListener interface

There are two methods declared in the ServletContextListener interface which must be implemented by the servlet programmer to perform some action such as creating database connection etc.

  1. public void contextInitialized(ServletContextEvent e): is invoked when application is deployed on the server.
  2. public void contextDestroyed(ServletContextEvent e): is invoked when application is undeployed from the server.

Example of ServletContextEvent and ServletContextListener

In this example, we are retrieving the data from the emp32 table. To serve this, we have created the connection object in the listener class and used the connection object in the servlet.

index.html

MyListener.java

MyListener.java


Example of ServletContextListener to create table of a project

In this example, we are creating table of the project. So we don’t need to create all the tables manually in the database.

MyListener.java

Other Examples of ServletContextListener


Example of ServletContextListener to improve performance

You may also like