Getting NPE when using getServletConfig().getServletContext().getAttribute() (Java)

前端 未结 1 1759
傲寒
傲寒 2021-01-27 04:32

I am using Servlets from not a long time. And i am getting this problem, which i can\'t terminate myself. I am using Servlets to create a small web project, and i tried to add m

1条回答
  •  暖寄归人
    2021-01-27 04:41

    Initialize your field in an overriden init(ServletConfig) method. The ServletConfig is not available at instance initialization time.

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.clientService = config.getServletContext().getAttribute("clientService");
    }
    

    From the javadoc of Servlet#init(ServletConfig)

    Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

    The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.

    The javadoc of the GenericServlet implementation of init(ServletConfig) further specifies

    This implementation stores the ServletConfig object it receives from the servlet container for later use. When overriding this form of the method, call super.init(config).

    0 讨论(0)
提交回复
热议问题