The javax.servlet Package  

A servlet is a small Java program that resides on a web server, and listens for and responds to requests from client machines. Servlets do not have a main() method, and can be thought of as being analogous to applets, except that they are running on the server side. The most common uses for servlets are processing and storing data submitted from an HTML form, providing dynamic responses to client requests, and managing state information for multiple client requests.

The life cycle of a servlet is governed by three methods defined in the Servlet interface. The init() method is called when the servlet is loaded into the address space of the server and provides initialization parameters to the servlet. The service() method is called when a request is made from a client machine. The destroy() method is used when the servlet is taken out of service to release any resources allocated to the servlet.

RequestDispatcher Interface  
public interface RequestDispatcher  
 

A RequestDispatcher is an object that sends requests from client machines to the appropriate resource (servlet, HTML file, etc.) on the server. The server creates the RequestDispatcher object, which is used as a wrapper around a particular resource. A RequestDispatcher object was intended to wrap servlets, but can be used to wrap any type of resource on a server.

Example: Using RequestDispatcher

In this example, a RequestDispatcher object is used to include some copyright information, contained in the file copyright.html, in a response. The contents of the file are included in the response by having the RequestDispatcher object invoke the include() method.

 
     import javax.servlet.*; 
     import java.io.*; 
     public class RDServlet extends GenericServlet { 
       public void service(ServletRequest request, ServletResponse response) 
               throws ServletException, IOException { 
         // A RequestDispatcher object is associated with an html file 
    RequestDispatcher rd = 
          
getServletContext().getRequestDispatcher("/copyright.html"); 
         // The ServletResponse object passed to the service() method is used 
         // to set the content type of the response and to return a PrintWriter 
         // object.  The PrintWriter writes a line of text to the client machine. 
     response.setContentType("text/html"); 
         PrintWriter pw = response.getWriter(); 
         pw.println("Java Programmer's Reference"); 
         // The "copyright.html" file is sent to the client machine by having 
         // the RequestDispatcher object invoke the include() method.  The 
         // include() method is used rather than the forward() method because 
         // the PrintWriter object had already been created. 
         rd.include(request, response); 
         pw.close(); 
       } 
     } 

The copyright.html file contains the following code:

 
            <BR><BR><BR> 
     Copyright 2000 Wrox Press, Ltd.<BR> 
     All rights reserved<BR> 
Servlet Interface  
public interface Servlet  
 

Every servlet must implement the Servlet interface. It declares the methods that govern the life cycle of the servlet as well as methods to access initialization parameters and information about the servlet

Example: A Simple Servlet

This example creates a simple servlet that returns the current date and time. It overrides the service() method to write the string representation of a Date object back to the client machine. The output from the servlet is set to be interpreted as HTML code.

 
            import javax.servlet.*; 
     import java.io.*; 
     import java.util.*; 
     public class SimpleServlet extends GenericServlet { 
       public void service(ServletRequest request, ServletResponse response) 
               throws ServletException, IOException { 
         response.setContentType("text/html"); 
         PrintWriter pw = response.getWriter(); 
         Date d = new Date(); 
         pw.println("<B>The date and time are " + d.toString()); 
         pw.close(); 
       } 
     } 
ServletConfig Interface  
public interface ServletConfig  
 

A ServletConfig object is used to pass parameters to a servlet during its initialization. The initialization paramters are a set of name-value pairs. The ServletConfig interface declares methods that can access the parameters as well return the name of the servlet and its associated ServletContext object. A ServletContext object contains information about the server on which the servlet resides.

Example: Reading Initialization Parameters

A servlet is initialized with a parameter read from the servlets.properties file. The parameter represents the name of a file. The ServletConfig object passed to the init()method is used to access the initialization parameter. If the parameter is read correctly, the file is opened and its contents written back to the client machine

Note that the servlet class name should not be used in the URL, but rather the name that is assigned to the servlet in the Servlet engine configuration file. The initialization parameter is associated with this name. If the servlet class name is written in the location window, the initialization parameter will not be accessed.

 
     import javax.servlet.*; 
     import java.io.*; 
     import java.util.*; 
     public class InitServlet extends GenericServlet { 
       String file, str; 
       // The ServletConfig object passed to the init() method is 
       // used to retrieve the value associated with the initialization 
       // parameter "filename". 
       public void init(ServletConfig config) throws ServletException { 
         file = config.getInitParameter("filename"); 
       } 
       public void service(ServletRequest request, ServletResponse response) 
               throws ServletException, IOException, FileNotFoundException { 
         response.setContentType("text/html"); 
         PrintWriter pw = response.getWriter(); 
         // If the initialization parameter was successfully read, its value 
         // is used to open a file.  The contents of the file are then sent 
         // back to the client machine. 
         if (file != null) { 
           BufferedReader br = new BufferedReader(new FileReader(file)); 
           while ((str = br.readLine()) != null) { 
             pw.println("<B>" + str + "<BR>"); 
           } 
         } else { 
           pw.println("initialization parameter does not exist"); 
         } 
         pw.close(); 
       } 
     } 

The web.xml file includes the following code:

            <web-app> 
       ... 
       <servlet> 
     <servlet-name>init</servlet-name> 
     <servlet-class>InitServlet</servlet-class> 
         <init-param> 
          
<param-name>filename</param-name> 
          
<param-value>webpages/WEB-INF/names.txt</param-value> 
     </init-param> 
       </servlet> 
       ... 
     </web-app> 

Finally, the names.txt file contains:

 
     Jackson's birthday is March 21 
     Zachary's birthday is May 12
ServletContext Interface  
public interface ServletContext  
 

The ServletContext interface declares methods that a servlet uses to communicate with its host server. The methods declared in this interface allow a servlet to obtain information about the server on which it is running.

Example: Using ServletContext

A ServletContext object is used to obtain information about the server on which a servlet is running. The ServletContext object is also used to obtain a second ServletContext object that is associated with another resource.

 
     import javax.servlet.*; 
     import java.io.*; 
     import java.util.*; 
     public class ServerInfoServlet extends GenericServlet { 
       String attributeName; 
       public void service(ServletRequest request, ServletResponse response) 
               throws ServletException, IOException { 
     response.setContentType("text/plain"); 
         PrintWriter pw = response.getWriter(); 
         // A ServletContext object is used to obtain information about 
         // the server. 
     ServletContext sc = getServletContext(); 
         pw.println("Server info is " + sc.getServerInfo()); 
         // Two additional attributes are added. 
         sc.setAttribute("status", "OK"); 
         sc.setAttribute("mood", "happy"); 
         pw.println(); 
         pw.println("Server Attributes"); 
         Enumeration e = sc.getAttributeNames(); 
         while (e.hasMoreElements()) { 
           attributeName = (String) e.nextElement(); 
           pw.println("name: " + attributeName + "  value: " 
                      + sc.getAttribute(attributeName)); 
         } 
    // The original ServletContext object can be used to obtain a 
         // ServletContext of another resource 
         pw.println(); 
         pw.println("Other resource info"); 
         String path = sc.getRealPath("/tmp.txt"); 
         ServletContext sc2 = sc.getContext(path); 
         pw.println("MIME type: " + sc2.getMimeType(path)); 
         pw.close(); 
       } 
     } 

Finally, the tmp.txt file contains:

 
            blah, blah, blah 
ServletRequest Interface  
public interface ServletRequest  
 

The ServletRequest interface declares methods that are used to provide client request information to a servlet. The information can include parameter name-value pairs, attributes, and an input stream. A ServletRequest object is passed to the service() method defined in the Servlet interface as well as the forward() and include() methods from the RequestDispatcher interface.

Example: Using ServletRequest

This example uses the ServletRequest object that is automatically passed to the service() method to access information about the request and about the client machine that made the request.

 
     import javax.servlet.*; 
     import java.io.*; 
     import java.util.*; 
     public class RequestServlet extends GenericServlet { 
       public void service(ServletRequest request, ServletResponse response)  
               throws ServletException, IOException { 
     response.setContentType("text/plain"); 
         PrintWriter pw = response.getWriter(); 
         // The ServletRequest object passed to the service() method is used 
         // to obtain information about the request and about the client machine. 
         pw.println("IP address of the client: "  
                    + request.getRemoteAddr()); 
         pw.println("Name of the client: " + request.getRemoteHost()); 
         pw.println("Character encoding: "  
                    + request.getCharacterEncoding()); 
         pw.println("Length of request: " + request.getContentLength()); 
         pw.println("Type of request: " + request.getContentType()); 
         pw.println("Request Protocol: " + request.getProtocol()); 
         pw.println("Request scheme: " + request.getScheme()); 
         pw.close(); 
       }  
     } 
ServletResponse Interface  
public interface ServletResponse  
 

The ServletResponse interface declares methods that are used to assist the servlet in sending a response to the client machine.

Example: Using ServletResponse

This example uses the ServletResponse object that is automatically passed to the service() method to send an image file back to the client machine. A ServletContext object is used to assign the image file to an InputStream. The ServletResponse object is then used to set the content type of the response and return the ServletOutputStream object used to write the image.

 
            import javax.servlet.*; 
     import java.io.*; 
     public class ResponseServlet extends GenericServlet { 
       int c; 
       public void service(ServletRequest request, ServletResponse response) 
               throws ServletException, IOException, FileNotFoundException { 
         // A ServletContext object is used to assign an image file to an 
         // InputStream 
         ServletContext sc = getServletContext(); 
         InputStream is = sc.getResourceAsStream("/gardening.jpg"); 
         // The ServletResponse object passed to the service() method is used 
         // to set the content type of the response and to return the 
         // ServletOutputStream object that is used to send the image file 
         // back to the client machine. 
     response.setContentType("image/jpg"); 
         ServletOutputStream sos = response.getOutputStream(); 
         while ((c = is.read()) != -1) { 
           sos.write(c); 
         } 
         is.close(); 
         sos.close(); 
       } 
     } 
SingleThreadModel Interface  
public interface SingleThreadModel  
 

The SingleThreadModel interface declares no methods. A servlet that implements this interface will allow only one request at a time to access its service() method. The server will achieve this by either sychronizing access to a single instance of the servlet or by assigning a separate instance of the servlet for each request.

GenericServlet Class  
public abstract class GenericServlet extends Object implements Servlet, ServletConfig, Serializable  
 
Object   
  GenericServlet   
Interfaces

Servlet, ServletConfig, Serializable

The GenericServlet class defines a generic, protocol-independent servlet. It provides implementations of the methods declared in the Servlet and ServletConfig interfaces. Because GenericServlet is an abstract class, a GenericServlet object is never created. To create a generic servlet, a class must be written that extends the GenericServlet class and overrides the service() method.

ServletInputStream Class  
public abstract class ServletInputStream extends InputStream  
 
Object   
   InputStream   
     ServletInputStream   

The ServletInputStream class is used to read binary data from a client request. It provides a method that can read the data one line at a time. Under some protocols (HTTP, POST, and PUT, for example), a ServletInputStream object can be used to read data sent from the client.

ServletOutputStream Class  
public abstract class ServletOutputStream extends OutputStream  
 
Object   
   OutputStream   
     ServletOutputStream   

The ServletOutputStream class is used to write binary data to a client machine. It provides overloaded versions of the print() and println() methods that can handle primitive and String datatypes.