servlets tutorial

HttpServlet Class in Servlet

HttpServlet Class is a GenericServlet extension that adds methods for dealing with HTTP-specific data. To handle specific sorts of HTTP requests (GET, POST, and so on), HttpServlet provides a number of methods such as doGet(), doPost(), and doPut(). These methods are often invoked by the default implementation of the service() function, which determines the type of request and then invokes the relevant method. Here’s an example of a HttpServlet:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<HTML>");
out.println(
"<HEAD><TITLE>Technosap Tutorials</TITLE></HEAD>");
out.println(
"<BODY><H1>Hello, World!</H1><H6>Again.</H6></BODY></HTML>");
}
}

HttpServlet Class

HelloWorldServlet demonstrates many essential servlet concepts. First, HelloWorldServlet extends HttpServlet. This is standard practice for an HTT servlet. HelloWorldServlet defines one method, doGet(), which is called whenever anyone requests a URL that points to this servlet. The doGet() method is actually called by the default service() method of HttpServlet.


The service() method is called by the web server when a request is made of HelloWorldServlet; the method determines what kind of HTTP request is being made and dispatches the request to the appropriate doXXX() method (in this case, doGet()). doGet() is passed two objects, HttpServletRequest and HttpServletResponse, that contain information about the request and provide a mechanism for the servlet to produce output, respectively.

If you define a doGet() function for a servlet, you may also wish to override HttpServlet’s getLastModified() method. If the content given by a servlet has changed, the server uses getLastModified(). If you define a doGet() function for a servlet, you may also wish to override HttpServlet’s getLastModified() method. If the content given by a servlet has changed, the server uses getLastModified().

The Servlet should also implement getServletInfo(), which returns a string that contains information about the servlet, such as name, author, and version (just like getAppletInfo() in applets). This method is called by the web server and generally used for logging purposes. This example explain how HttpServlet Class works.