ServletContextEvent and ServletContextListener in Jakarta EE Servlet

ServletContextEvent and ServletContextListener are two objects of Jakarta EE Servlet that are responsible for recording and handling changes in the ServletContext of a web application when this web application is deployed to the Server Runtime. Any changes to the ServletContext, the ServletContextEvent will log and the ServletContextListener will also implement those changes.

These changes will happen when the application is deployed and when we stop the application. You can add code so that when the application runs up or stops, some operations will be performed depending on your needs. To do this, create a new custom class that implements the ServletContextListener interface as follows:

Then declare this custom class in the web.xml file as follows:

Or you can also use the @WebListener annotation with the above custom class:

Just one of two ways!

Now, when you run the application, you will see the code inside the contextInitialized() method called as follows:

If you stop the Server Runtime, you will see the code in the contextDestroyed() method being called:

Add Comment