Before going into the details of ServletContextListener we should understand what is ServletContext. ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application. ServletContextListener is a interface which contains two methods:
public void contextInitialized(ServletContextEvent event) public void contextDestroyed(ServletContextEvent event)
The main feature of ServletContext is that it performs actions defined within the two methods above, respectively when a web-application is deployed or undeployed. For example it can be useful if we want set values or initialize objects when a web-app is deployed. Now let’s see how to define a custom Servlet Context Listener Class. Let’s call our class “MyContextListener“. It must implements the interface ServletContextListener and the inherited methods as showed below:
public class MyContextListener implements ServletContextListener{ @Override public void contextDestroyed(ServletContextEvent arg0) { // Code executing on web-app undeploy } @Override public void contextInitialized(ServletContextEvent arg0) { // Code executing on web-app deploy } }
Now we need to declare the listener in web.xml file, to ensure that the class will be called on deploy, in the following way:
<listener> <listener-class> com.myapp.MyContextListener </listener-class> </listener>
Of course, it’s possible to define several Context Listener in our web-application. Now we can see a very simple example in which we’re going to use the MyContextListener class to read params from Servlet Context. Adding the following lines in the web.xml file it’s possible to set automatically parameters in the Servlet Context when the web-app will be deployed:
<context-param> <param-name>MY_PARAM</param-name> <param-value>1234</param-value> </context-param>
Define params in this way can be useful when we don’t want define values in hard coded way, for example the properties file’s name used from a web-apps at deploying time. Below it’s showed the code for read the param defined in ‘web.xml’ and setted in the servlet context:
public void contextInitialized(ServletContextEvent sce) { // Fetching context-param from web.xml String myParam = sce.getServletContext().getInitParameter("MY_PARAM"); System.out.println(myParam); // It will print '1234' }