问题描述:

This question already has an answer here:

  • How do servlets work? Instantiation, sessions, shared variables and multithreading

    6 answers

网友答案:

I took the below code from Tomcat 8 Source code which is loading the servlet and calling init() of the servlet.

Full source code available here.

   @Override
    public synchronized Servlet loadServlet() throws ServletException {
        if (singleThreadModel) {
            Servlet instance;
            try {
                instance = existing.getClass().newInstance();
            } catch (InstantiationException e) {
                throw new ServletException(e);
            } catch (IllegalAccessException e) {
                throw new ServletException(e);
            }
            instance.init(facade);
            return instance;
        } else {
            if (!instanceInitialized) {
                existing.init(facade);
                instanceInitialized = true;
            }
            return existing;
        }
    }

This page from Head first servlets & JSP book explains the lifecycle clearly,

For more details, I recommend to read Head First Servlets & JSP

网友答案:

init() initialize servlet object on the request, not that its not called for each access , only on the creation of servlet service() creates threads for each request after deciding which method to run

相关阅读:
Top