How a Servlet is initialized by Servlet Container

Points To Remember
  • Servlets are initialized by the servlet containers.
  • Servlets like any other java class can have constructors.
  • Servlet needs an object of ServletConfig for initialization.
  • Interfaces cannot have constructors.
Why a Servlet is initialized using init() method ?
A servlet is a java class that implements javax.servlet.Servlet interface.A servlet can be given some init parameters in web.xml, called the ServelConfig and some global init parameters called the ServletContext. Thus they both are required at the initialization time of a servlet.

Also Servlet is an interface so it cannot have a constructor, so how will we pass the ServletConfig  object to the servlet for its initialization. This is the reason the Servlet interface have a init(ServletConfig config) method and the implementing class needs to override this method to pass a ServletConfig object to it.

GeneralServlet is an abstract class that implements the Servlet interface for us and helps in initialization of servlets by passing the ServletConfig object to the init() method of the Servlet interface.
Summary : Why we use init() for Servlet initialization
  • For a servlet to be initialized we need a ServletConfig Object.
  • Interfaces cannot have a constructor, so the only way is to get the ServletConfig object in the implementing class of javax.servlet.Servlet interface and then pass it to some method, so we created a method in the Servlet interface and called it init().
  • Now all the classes that implement Servlet interface will have to override init() method and pass a ServletConfig object to this method.
  • This will give the servlet container all necessary control to initialize the servlet.

No comments:

Powered by Blogger.