Explain the architecture of a Servet package.
Architecture of Servlet Package:The javax.servlet package provides interface and classes for writing servlets. The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet or Generic Servlets. For class GenericServlet, or a class extending it, the main method involved in client interaction is the service(ServletRequest, ServletResponse) method. For class HttpServlet, the default Http request type is 'GET' and the main method called to handle this is the method doGet(HttpServletRequest, HttpServletResponse).
Three methods are central to the life cycle of a servlet. These are init( ), service(),and destroy( ). They are implemented by every servlet and are invoked at specific times by the server.
Example of Simple Servletimport java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
The program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables the servlet to read data that is provided via the client request. The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.