What is Servlet Container
Normal Java application’s starting point is Main(public static void main(String args)) method. When ever java application needs to start, main method of the application should be invoked. But in case of Servlet this is not true, Servlet doesn’t contain any main method. So who will initiate and run the method of Servlet. It’s Container who has the full control of Servlets. It is container which is responsible to manage the life-cycle of servlet. Web server hands the request to web container in which servlet is deployed and not to Servlet itself. Then container provides request and response to servlet. It is container which calls the servlet’s method. Tomcat is the example of Servlet container.
How it works
When ever user request for any resource from Server Web server(Apache) will pass the request to Servlet Container(Tomcat) instead of directly to servlet. It is container who will create request and response Object and then pass it to Servlet eligible for asked resource and invoke service method of Servlet.
Services Provided by Container
- Lifecycle management of servlet
- Multithreading support for servlet
- Security provide
- JSP support
- Provides communication between web server and servlet
- Communication Support
Servlet Life Cycle
- Servlet Instantiation by no-arg Constructor run.
- init() method will be called. This method called once in the life cycle of servlet. Internally init(ServletConfig) is called which internally call init() method.
- Servlet is initialized and will be in this state till it is destroyed. Till then all request will go through service() method. Each request will run in separate thread.
- destroy() method will be called by Container to clean up all the resource. Here lifecycle of servlet will finish.
It is the ServletConfig which transform an Object to Servlet. Container provides servletcofig to servlet via init() method.
- Used to provide deploy-time information to the servlet.
- One servletConfig per servlet will be created.
- Can be used to access to access servletContext.
- ServletContext per web application will be created.
- Used to access web app parameter.
- Will be available to all the servlet in application.
Note: HttpServletRequest and HttpServletResponse are interfaces. It is container which implements given interface