|
Page 3 of 6
Once it is completed, it should look like below.
Now, the most important thing is that we need to make the class “implements” the ServletContextListener. So here is my latest ServletListener.java.
Now, we have an error in our class. Why? Because once we try to implement the javax.servlet.ServletContextListener interface, we need to define a few implementation methods for it. That’s why I mentioned earlier that it is the pre-defined interfaces. This is where our job will be started. You need to add two methods for it.
- public void contextInitialized(ServletContextEvent arg0)
- public void contextDestroyed(ServletContextEvent arg0)
So here is my latest ServletListener.java
public class ServletListener implements javax.servlet.ServletContextListener {
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("Servlet Context is initialized....");
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Servlet Context is destroyed....");
}
}
|
Okay, logically, if our web application is started, the contextInitialized method is executed. If our web application is removed (perhaps shutting down / redeploying web application in Tomcat), contextDestroyed method is executed.
Now, we need to add one more entry in our web.xml.
<listener>
<listener-class>com.mycompany.listener.ServletListener</listener-class>
</listener>
One thing you need to know that this listener entry MUST be before the <servlet> entry (if any). So here is my latest web.xml looks like.
After that, we can run the project to test our first Listener which is ServletContextListener.
|
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.