What is ServletContextListener?

Some times your init parameter is not sufficient always. When you need an init parameter that is a database DataSource. Init parameter can hold only String type. So how could you initialize a webapp with an object?
Sometimes the setAttribute() is also not enough. Consider there is an employee object has to be shared among the servlets through context.setAttribute() method. But in which servlet we have to keep the setAttribute() method that must be initialized first before other. So which servlet start first? The servlet might start after another servlet which has a getAttribute() method. What happens then?
To avoid this problem we need ServletContextListener.

We can make the separate class that can listen for the two key events in servlet’s life, initialization and destruction. That separate class must implement the javaz.servlet.ServletContextListener interface. So we need the separate class which get notified when the context is initialized and when the context is destroyed.

Import javax.servlet.*;
Pubic class MyServletContextListener implements ServletContextListener{
Public void contextInitialized(ServletContextEvent se){
//code to initialized the database}
Public void contextDestroyed(ServletContextEvent se){
//code to close the database}
To tell container about the listener, you have to configure it in web.xml file inside the <web-apps>tag. Like this

No comments:

Post a Comment