Java Servlet Listener-ServletContextListener example

This tutorial shows you Java Servlet Listener-ServletContextListener example then you know how can listen to the startup of web application with ServletContextListener. You should know that ServletContextListener allows you to initialize application when it is deployed and free resources when the application is destroyed. This is seventh post of series of Java Servlet Tutorial. This series tutorial will provide you full knowledge about Servlet 3.0.

Table of contents
1. Project structure
2. Maven Dependency
3. Implement CustomStartUpListener to listener on startup
4. Deploy ServletContextListener example

Project structure

Servlet Context Listener Example

Maven Dependency

Implement CustomStartUpListener to listener on startup
To listen to the event on startup you should implement your servlet listener from the javax.servlet.ServletContextListener class and add the Servlet 3 @WebListener annotation to be enable application startup listener. The implementation requires to add two methods: public void contextInitialized(ServletContextEvent event) and public void contextDestroyed(ServletContextEvent event). These two methods help you to manipulate the initialization and destroy phases of web application.

Here is the detail of implementation

We notice that if you prefer the web.xml servlet descriptor instead of using the @WebListener annotation you should add the context listener configuration as follows:

Deploy ServletContextListener example
For demonization, we put file war into a web container (into the webapps directory of Tomcat 8 for example) then the contextInitialized() method is invoked such as the screen shoot.

Java Servlet Listener-ServletContextListener example

When we destroy our application then the contextDestroyed() method is invoked such as the screen shoot.

Java Servlet Listener-ServletContextListener example

That’s it on the tutorial Java Servlet Listener-ServletContextListener example and ultil now you know how to implement your own ServletContextListener. You can also find other servlet example in the series of Java Servlet Example.

Download complete source code, click link below

Servlet-Context-Listener-Example.zip (48 downloads)

Happy learning!

Leave a Comment

*

Please share it if you found this useful
Hide Buttons