«^»
3.4. An example of a servlet

For a simple example of a servlet, suppose we want a WWW page that delivers the current date and time. In Java, we can easily use java.util.Date to output the current date and time:

0001: Date tDate = new Date();
0002: String tDateString = tDate.toString();
0003: System.out.println(tDateString);

How can we convert this code to code that can be executed as a servlet? One way is to produce a class that is derived from the HttpServlet class (that is in the javax.servlet.http package). If our class overrides HttpServlet's doGet method, the webserver program will arrange for our doGet method to be executed when someone visits the appropriate WWW page.

Here is the code of a getDateAndTime servlet:

0004: import java.util.          Date;                      // getDateAndTime.java
0005: import javax.servlet.http. HttpServlet;
0006: import javax.servlet.http. HttpServletRequest;
0007: import javax.servlet.http. HttpServletResponse;
0008: import java.io.            IOException;
0009: import java.io.            PrintWriter;
0010: import javax.servlet.      ServletException;
0011: public class getDateAndTime extends HttpServlet
0012: {
0013:    public void doGet(HttpServletRequest request,
0014:                      HttpServletResponse response)
0015:          throws IOException, ServletException
0016:    { 
0017:       Date tDate = new Date();
0018:       String tDateString = tDate.toString();     
0019:       response.setContentType("text/html");
0020:       PrintWriter tResponsePrintWriter = response.getWriter();
0021:       StringBuffer tStringBuffer = new StringBuffer();
0022:       tStringBuffer.append("<html>\n" );
0023:       tStringBuffer.append("<title>Clock</title>\n" );
0024:       tStringBuffer.append("It is now " + tDateString + "\n" );
0025:       tStringBuffer.append("</html>\n" );
0026:       tResponsePrintWriter.println(tStringBuffer);
0027:       tResponsePrintWriter.close();
0028:    }
0029: }

When the doGet method gets called, it is passed two arguments (request and response):