Java Servlet Container tutorial for beginners

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

  1. Lifecycle management of servlet
  2. Multithreading support for servlet
  3. Security provide
  4. JSP support
  5. Provides communication between web server and servlet
  6. Communication Support

Servlet Life Cycle

  1. Servlet Instantiation by no-arg Constructor run.
  2. 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.
  3. 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.
  4. 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.

ServletConfig

  • 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

  • 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

 

About the author

J Singh

Main brain behind this blog/QnA site. She has written all these article as per her personal experience. She has published it mainly to help beginners. These articles might have some problems. So bear with her and let her know if you find any problem in any of the article.

5 Comments

Leave a Comment