Generating a Response

Besides the request object, the container passes an object that implements the HttpServletResponse interface as an argument to the doGet( ) and doPost( ) methods. This interface defines methods for getting a writer or stream for the response body. It also defines methods for setting the response status code and headers. Example 19-3 contains the code for a servlet that uses some of the methods.

Example 19-3. Using HttpServletResponse methods
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
  
public class HelloMIME extends HttpServlet {
    private static final int TEXT_TYPE = 0;
    private static final int IMAGE_TYPE = 1;
  
    public void doGet(HttpServletRequest request, 
        HttpServletResponse response) 
        throws ServletException, IOException {
  
        String greeting = "Hello World!";
        int majorType = TEXT_TYPE;
        String type = request.getParameter("type");
        if ("plain".equals(type)) {
            response.setContentType("text/plain");
        }
        else if ("html".equals(type)) {
            response.setContentType("text/html");
            greeting = "<html><body><h1>" + greeting +
                "</h1></body></html>";
        }
        else if ("image".equals(type)) {
            response.setContentType("image/gif");
            majorType = IMAGE_TYPE;
        }
        else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, 
                "Please specify a valid response type");
            return;
        }
  
        if (majorType == TEXT_TYPE) {
            PrintWriter out = response.getWriter(  );
            out.println(greeting);
        }
        else {
            OutputStream os = response.getOutputStream(  ); ServletContext application = getServletContext( ); InputStream ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.