Sunday, April 26, 2009

The Servlet API

Servlet is the main Interface. GenericServlet implements Servlet and is an abstract class having overloaded init methods.

init()
init(ServletConfig sc)

HttpServlet extends GenericServlet and is also an abstract class and inherits both the overloaded init methods. MyServlet extends HttpServlet and thus it also inherits the overloaded init methods.

The need for 2 init methods in the GenericServlet class. 

With only one Init

public class GenericServlet
{
ServletConfig sc;
public void init(Servletconfig sc)
{
this.sc = sc;
}
}

Now this servletconfig object is available to HttpServlet and to all the classes which extends httpServlet.

public class MyServlet extends HttpServet
{
// now i have to write my own init functionality so i override the init method.
// by doing this, I have lost the functionality of the GenericServlet's init method and thus
     // lost the ServletConfig object. 

public void init(ServletConfig sc)
{
// my own functionality 
}
}

Thus to avoid this and to have the servletconfig object always. Programmers then need to write their own servlet class and call super to save the servletconfig object.

The above code can be re written as 

public class MyServlet extends HttpServet
{
// now i have to write my own init functionality so i override the init method.
// I retain the servletconfig object by calling super.init(servletconfig), thus i still have 
// access to the servletconfig object 

public void init(ServletConfig sc)
{
super.init(servletconfig);
// my own functionality 
}
}

Thus every time I write my own servlet class, in the init method I need to call super.init(servletconfig). To avoid this, an init method was added in the genericservlet class and design changes were as follows.

public class genericservlet
{
servletconfig sc;
public void init(servletconfig sc)
{
this.sc = sc;
init();
}

public void init()
{
// a do nothing method, waiting to be overridden
}

}

public class myservlet extends httpservlet 
{
public void init()
{
// init method overridden and the programmer still has the access to the servletconfig   // object. since the container calls the init(servletconfig sc) method everytime it need to  
      // initialize the servlet.
}
}