Home Segments Top Top Previous Next

1041: Mainline

The easiest way to define a servlet is to extend the HttpServlet class, shadowing the doGet method. That method has two parameters: the request parameter's value is a class instance that contains information about the request (ignored in the following example); the response parameter's value is a class instance that your program uses to convey information back to the browser from which the request originated.

The setContentType method prepares the response instance to receive the text of an HTML page. The getWriter method obtains an output stream on which to write text, which happens to be an instance of the PrintWriter class.

Once doGet completes, the servlet server returns the information contained within the response instance to the client, to be displayed by the browser as a new HTML page. Evidently, doGet is so named because it gets a new HTML page.

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class GetCriticFormServlet extends HttpServlet {  
 public void doGet (HttpServletRequest request, HttpServletResponse response) 
             throws ServletException, IOException { 
  response.setContentType("text/html"); 
  PrintWriter output = response.getWriter(); 
  output.println("<HTML><HEAD><TITLE>"); 
  output.println("You be the critic!"); 
  output.println("</TITLE></HEAD><BODY>"); 
  // HTML content, such as the form shown in Segment 1043, 
  // printed to output stream here using println 
  output.println("</BODY></HTML>"); 
  output.flush(); 
 } 
}