How can I write custom servlet context init method

前端 未结 2 1319
栀梦
栀梦 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: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
    
       }
    }
    

提交回复
热议问题