Wednesday, March 17, 2010

Basic Servlet Structure

A servlet is a small Java program that runs within a Web server.Servlets receive and respond to requests from Web clients,usually across HTTP, the HyperText Transfer Protocol.

To write a Servlet Class we follow some basic steps.
1.Implement the Servlet interface available in javax.servlet package(javax.servlet.Servlet).
2.The acees speifier for your servlet class must be public.

Syntax:
 public class BasicServlet implements Servlet
 {
                   // Here we have to implement all methods in Servlet inteface.

  }

Methods in Servlet Inteface:

public void init(ServletConfig config) throws ServletException
{

}

By seeing the above method,we easily understand the init(ServletConfig config) always throws ServletException.So we have to handle when we implement our own Servlet class.

An Example to Implement init(ServletConfig config) method with some different syntax
Ex 1:
import javax.servlet.*;
public class SampleServlet implements Servlet
{
       public void init(ServletConfig config)
       {
                  try
                 {
                         //your code

                  }
                  catch(ServletException se)  { se.printStackTrace(); }
        }

// implement remaining all methods availabe in Servelt interface with some code to properly compile the java file
}

Ex 2:
import javax.servlet.*;
public class SampleServlet implements Servlet

{
       public void init(ServletConfig config) throws ServletException
       {

                    // your code
       }
// implement remaining all methods availabe in Servelt interface with some code to properly compile the java file

}

By seeing the above two examples,it is clear that when ever we write init(ServletConfig config) method ,it is not necessary to declare throws ServletException for inti(ServletConfig config) method.
    For informing the ServeltContainer to say initilization failed we are throwing ServletException to not to put  Servelt Object in service,instead of explicity handling ServletException using try/catch blocks.If we are handling exception explicity how to inform the container about init() fail.Is there any solution in this case.Think your self.

1 comment: