Saturday, March 15, 2008

Servlet Instantiation

Step 1.
Container reads the Deployment descriptor and read the servlets class name element value
say for example:


<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.mycompany.MyServlet</servlet-class> <!-- This value will be read.
<init-param>
<param-name>myVariable</param-name>
<param-value>1</param-value>
</init-param>
</servlet>

Step 2:
The container loads the class
Class clazz = Class.forName("com.mycompany.MyServlet");

Step 3:
Creates an Instance of the Servelt class,
Servlet objServlet = clazz.newInstance();

The above step will invoke the default contstructor (Zero parameter constructor of the servelt class. The spec dictates that Servlet Code should have a constructor with zero paremeter i.e default constructor).

Step 4:
The container then reads the initialization parameter "init-param" xml tags, and constructs a ServletConfig object and inovkes the
objServlet.init(config)


In simple words the ServletContainer instantiates your servlet. Since ServletContainer does not know what are the parameters to be passed, it calls default constructor i.e. with no arguments

A servlet is still just a class, so of course you can instantiate it. You can even have constructors taking arguments.

like..MyServlet = new myServlet();


But for the container to be able to use your servlet, it needs a public no-argument constructor. It would also not really make sense to instantiate the servlet yourself, because the container is responsible for the life cycle.

No comments: