Generating Responses of Different Types
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 4-2 contains the code for a
servlet that uses some of these methods.
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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 ...
Get JavaServer Faces 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.