I am learning servlets and I know that servlet lifecycle will be call at the time of loading of servlet or whenever request sent to servlet. But how the web container knows at the time of loading of servlet I need to call Servlet init method or at the time of request came I need to call Service() method? I want know how exacty web container internally invoking init(), Service() Method at the time of loading of servlet and request sent by client at code level?
Asked
Active
Viewed 341 times
2 Answers
1
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

Sundararaj Govindasamy
- 8,180
- 5
- 44
- 77
-
Thanks for your reply. but my question is at code level which class is calling init method. Can I see internal code for more understanding? what exactly is happening inside. – Bat Sep 30 '16 at 07:20
-
0
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

Amer Qarabsa
- 6,412
- 3
- 20
- 43