![]() |
![]() |
||||
A context listener receives notifications when the web application (ie: the context) is starting up or shutting down.
To create a Context Listener, create a class which implements the ServletContextListener interface.
This involves implementation of the following two methods:
public void contextInitialized(ServletContextEvent servletContextEvent);
|
Each listener class must also have a public constructor taking no arguments.
This method is called whenever the application starts up.
This method is called whenever the application is shutting down.
The ServletContext is passed to both of the above methods in the ServletContextEvent
object.
It can be retrieved as follows:
ServletContext servletContext = servletContextEvent.getServletContext();
|
This object has setAttribute(), getAttribute() and removeAttribute() methods which can be used to store context-specific information.
import javax.servlet.*;
|
Add the above class to WEB-INF/classes, and add the following in web.xml to activate our new ContextListener.
<listener> <listener-class>MyContextListener</listener-class> </listener>
Note that the above class was not put in a package, so no package name is specified in the <listener-class> tag.