How can I write custom servlet context init method

前端 未结 2 1320
栀梦
栀梦 2021-01-25 13:59

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

相关标签:
2条回答
  • 2021-01-25 14:32

    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.

    0 讨论(0)
  • 2021-01-25 14:42

    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
    
       }
    }
    
    0 讨论(0)
提交回复
热议问题