Servlet – Context Event and Context Listener
ServletContextEvent class provides alerts/notifications for changes to a web application’s servlet context. ServletContextListener is a class that receives alerts/notifications about changes to the servlet context and acts on them. When the context is initialized and deleted, the ServletContextListener is utilized to conduct crucial tasks. In a nutshell, ServletContextEvent and ServletContextListener function in tandem; anytime the ServletContext changes, ServletContextEvent broadcasts a notice, which is received by ServletContextListener, which then performs various duties based on the message.
Constructor of ServletContextEvent Class
In the ServletContextEvent class, there is just one constructor. After the ServletContext instantiation, the web container produces an instance of ServletContextEvent.
Methods of ServletContextEvent
public ServletContext getServletContext()
Note: It returns the instance of ServletContext.
Methods of ServletContextListener Interface
|void contextInitialized(ServletContextEvent e)||When the application is first initialized, this method is called.|
|void contextDestroyed(ServletContextEvent e)||When the application is destroyed, this method is called.|
Example: ServletContextEvent and ServletContextListener
In this example, we will have to create a table named counter with a column named pageview to save the number of pageviews. by using this database record we will find out the total number of page views.
A. File: index.html
B. File: web.xml
C. File: MyListenerGfg.java
D. File: CounterGfg.java
Now, run ‘index.html’ file on server and this will show the following output
After clicking on that link following page will be loaded which shows the count of page views means how many times the user visited the page. The page count will be increased every time you refresh or revisit the page.