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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.huongdanjava.jakartaee; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; public class HuongDanJavaServletContextListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("contextDestroyed"); } @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("contextInitialized"); } } |
Then declare this custom class in the web.xml file as follows:
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0"> <listener> <listener-class>com.huongdanjava.jakartaee.HuongDanJavaServletContextListener</listener-class> </listener> </web-app> |
Or you can also use the @WebListener annotation with the above custom class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.huongdanjava.jakartaee; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.servlet.annotation.WebListener; @WebListener public class HuongDanJavaServletContextListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("contextDestroyed"); } @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("contextInitialized"); } } |
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: