HttpServlet ClassThe next several sections of this chapter describe the technical details of writing a Java servlet. Like any other Java program, the code to implement a Java servlet is contained in a class. This chapter will focus on servlets that respond to HTTP commands. The HttpServlet class defined in the javax .servlet.http package can be used to create an HTTP servlet. The header for the HttpServlet class is:
You will notice that HttpServlet is an abstract class, so you won't use the HttpServlet class directly, but instead write a subclass of it. The HttpServlet class defines a number of methods for responding to an HTTP request. The headers of these methods are
There is one method for each of the seven HTTP commands. For instance, the doGet() method corresponds to the HTTP GET command. When the Java web server receives a client request, the Java runtime will call one of these methods according to the type of HTTP command. If an HTTP GET command is received, the doGet() method is called, and so on. These methods as defined in the HttpServlet class are stubs (methods with no body). It is up to subclasses of HttpServlet to provide implementation of one or more of these methods. Each method takes two input arguments. The HttpServletRequest object is used to extract the input parameters that accompanied the HTTP command. The HttpServletResponse object is used to send the output data back to the client. These input arguments are generated automatically by the system by the container that creates and controls servlets for the web server. You never need to worry about creating an HttpServletRequest or HttpServletResponse object. |