I wish to set up a few application wide variables with servletContext.setAttributes on servlet context initialization phase .How can I achieve this.
If you would like to tie your logic closer to the servlet (and not use a listener), you can override the servlets init
method. Like so:
@Override
public void init() throws ServletException {
ServletContext sc = getServletContext();
// Store our attribute(s)!
// Check first to make sure it hasn't already been set by another Servlet instance.
if (sc.getAttribute("key") == null)
sc.setAttribute("key", "value");
}
And you don't have to call through to super.init(config)
. See docs.
Implement javax.servlet.SevletContextListener
which gets a callback when javax.servlet.ServletContext
is initialized.
Here is the example:
public class MyServletContextListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent sce)
{
ServletContext sc = sce.getServletContext();
//do your initialization here.
sc.setAttribute(.....);
}
public void contextDestroyed(ServletContextEvent sce)
{
ServletContext sc = sce.getServletContext();
//do your cleanup here
}
}