Previous Table of Contents Next


Processing Responses

When one of the processing methods of HTTPServlet is called, the typical steps are to read the values from the request, do any additional processing such as logging or database access, and then write a response to the client.

To write a response to the client, HttpServletResponse has a method getWriter that returns a PrintWriter instance. Use this object to write data to the client. All HTTP responses are expected to include a content type. Because the servlet is handling a specific client request, the servlet should define this type as shown above. The value for this content type is included in the HTTP header returned to the client. Possible content types include text/html, text/plain, image/gif, and any other valid MIME type. Notice that the type is separated into a major and minor type. All text uses the text major type but can either be HTML or plain. Images use the image major type and can use a number of minor types, including gif, jpg, and tiff. The list of acceptable types is constantly growing. New types are often tested using the x- prefix to indicate that they are experimental. You can find more information about the available types by browsing to www.ietf.org/ and looking for a request for comments (RFC) search engine. Then go to RFC 2046. These RFCs can be hard to read, so the other option is to use your browser’s preferences dialog to find a list of the types it supports.

In the example that follows, if you don’t specify that the data you are sending is HTML, the browser parses HTML tags as regular text and just displays the text. For example, rather than seeing a horizontal rule, you would see <HR> in the browser. To specify the content type for a servlet’s response, call the HttpServletResponse method setContentType and pass in an appropriate type. For example, the following line:

response.setContentType(“text/html”);

tells the browser we are sending HTML.

Example Servlet

The code that follows defines a basic servlet BookReviewServlet that can be used in place of the CGI program used to display the book review in the section “Processing Forms with CGI.” The only change to the HTML file is the <FORM> tag. The new tag looks like this:

<form action=<http://localhost:8080/servlet/BookReviewServlet> method=POST>

In the BookReviewServlet code, the servlet performs the same function as the Perl script by processing the form request and sending back an HTML response page. For simplicity, only POST is supported.

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class BookReviewServlet extends HttpServlet
{
    // Write a response to the client.
    public void doPost(HttpServletRequest req,
                       HttpServletResponse res)
        throws ServletException, IOException
    {
        /*
          Set the “content type” header of the response so that
          the browser knows we are sending HTML, not just raw
          text. If you don't do this, the HTML tags will not
          be interpreted.
          Try commenting out this line to see what happens.
        */
        res.setContentType(“text/html”);

        //Get the response's PrintWriter to return text to client.
        PrintWriter toClient = res.getWriter();

        // Read form values.
        String fName = req.getParameter(“fname”);
        String chp = req.getParameter(“favchap”);
        String writeServlet = req.getParameter(“writeservlet”);

        // Respond to client with a thank you.
        toClient.println(“<HTML>”);
        toClient.println(“<TITLE>Book Review Response</TITLE>”);
        toClient.print(fName);
        toClient.println(“, thank you for your feedback.<BR>”);
        toClient.print(“Your favorite chapter so far is chapter ”);
        toClient.println(chp + “.<BR>”);
        toClient.println(“<HR>”);
        toClient.println(“You are ”);
        if(writeServlet == null)
            toClient.print(“not ”);
        toClient.println(“planning to write a servlet.”);

        toClient.println(“</HTML>”);


        // Close the writer when response is done.
        toClient.close();
    }

}

Also notice that doService() is a synchronized method. This is because servlets typically run in multithreaded environments. Because there is only one instance of the servlet object created by the Web server, the servlet must be able to service simultaneous requests. Servlets, therefore, need to ensure that they synchronize access to such shared resources as their instance variables, database connections, and file streams.

Running the Servlet

JSDK includes a testing application called servletrunner in the JSDK/bin directory. Put your compiled servlet in the examples directory of the JSDK and then execute servletrunner. If you make any changes to your servlet, restart the servletrunner. To load the servlet from the Web browser, specify the location http://localhost:8080/servlet/ServletName. If servletrunner is on another machine, replace localhost with the server name. Port 8080 is the default port that servletrunner is on.


Previous Table of Contents Next