Lopakhin
Lopakhin

Reputation: 299

How can I write custom servlet context init method

I wish to set up a few application wide variables with servletContext.setAttributes on servlet context initialization phase .How can I achieve this.

Upvotes: 1

Views: 5651

Answers (2)

Martin Andersson
Martin Andersson

Reputation: 19563

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.

Upvotes: 1

Ramesh PVK
Ramesh PVK

Reputation: 15446

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

   }
}

Upvotes: 1

Related Questions