How can I write custom servlet context init method

前端 未结 2 1351
栀梦
栀梦 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.

提交回复
热议问题