- Objectives
- Introduction
- Overriding HttpServlet GET, POST, and PUT Methods
- Triggering HttpServlet GET, POST, and PUT Methods
- Interfacing with HTML Requests
- Web Application Scope
- Servlet Life-cycle
- Using a RequestDispatcher
- Web Application Context
- Context Within a Distributable Web Application
- Chapter Summary
- Apply Your Knowledge
Interfacing with HTML Requests
In this section we deal with interfacing with HTML requests: how to process them and how to return a response to one. Since the HTTP client is sending the request, how do you know what it wants? While the container handles things like parsing the request and placing the information into a Request object, sometimes you have manually code processing routines. This section tells you how to write these routines that perform actions such as retrieve HTML form parameters, request headers, servlet initialization parameters, and redirects.
1.3 For each of the following operations, identify the interface and method name that should be used to
- Retrieve HTML form parameters from the request
- Retrieve a servlet initialization parameter
- Retrieve HTTP request header information
- Set an HTTP response header; set the content type of the response
- Acquire a text stream for the response
- Acquire a binary stream for the response
- Redirect an HTTP request to another URL
This is a broad-stroke objective. It is asking you to be familiar with the most important servlet interfaces and their methods. Thankfully, this objective reduces the task from remembering almost 1,000 methods to just a few of them, which happen to be the most interesting ones.
Form Parameters
The interface that defines the form parameter methods is ServletRequest. This interface is implemented by the Web container to get the parameters from a request. Parameters are sent in the query string or posted form data. The four methods associated with getting parameters are
getParameter(String). You use this method if you know the particular parameter name. It returns the value of a request parameter as a string, or null if the parameter does not exist. Use this method when you are sure the parameter has only one value; otherwise use getParameterValues(). Be careful: If you use this method with a multivalued parameter, you won't get an error. You will get the first value in the array returned by getParameterValues().
getParameterMap(). You use this method to create a map of the form parameters supplied with this request.
getParameterNames(). This one returns an Enumeration of string objects containing the names of the parameters contained in this request, or an empty Enumeration if the request has no parameters.
getParameterValues(String). This method returns an array of values as strings, or null if the parameter does not exist. If the parameter has a single value, the array has a length of 1. One of the common uses of getParameterValues() is for processing <select> lists that have their "multiple" attribute set.
Listing 4.7, the following code snippet, demonstrates how you would grab the parameters from a request.
Listing 4.7 Servlet That Walks the Request Parameter List
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowRequestParameters extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Enumeration parameterNames = request.getParameterNames(); // acquire text stream for response PrintWriter out = res.getWriter (); while (parameterNames.hasMoreElements()) { String name = (String)parameterNames.nextElement(); String value = request.getParameter(name); out.println(name + " = " + value + "<br/>"); } } }
Retrieving a Servlet Initialization Parameter
A Web application includes many parts; it rarely is just one class or file. It can be a combination of JSP pages, servlets, tag libraries, Java beans, and other class files. The Java Virtual Machine creates a memory box for all of these called a ServletContext object which maintains information (context) about your Web application. You access the ServletContext for information about the application state. As the API states, the ServletContext allows you access many types of information. You can get application-level initialization parameters. You can also set and get application attributes, as well as the major and minor version of the Servlet API that this Servlet Container supports. One very interesting capability is to get hold of RequestDispatcher object to forward requests to other application components within the server, or to include responses from certain components within the servlet and to log a message to application log file. The ServletContext object is how you can set, get, and change application (not session) level attributes and talk to the Servlet Container.
Context means application scope. The getInitParameter and getInitParameterNames methods retrieve context-wide, application-wide, or "Web application" parameters. The getInitParameter method returns a string containing the value of the parameter (you provide the name), or null if the parameter does not exist.
Some parameters have no information, so this method will return a string containing at least the Servlet Container name and version number. The getInitParameterNames method retrieves the names of the servlet's initialization parameters as an Enumeration of string objects. If there aren't any, it returns an empty Enumeration. Be careful; don't confuse this with session-wide attributes.
Listing 4.8 shows an example of displaying servlet initialization parameters.
Listing 4.8 Servlet That Walks the Context Initialization Parameter List
import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; public class InitializationParameters extends HttpServlet { /** * Print servlet configuration init. parameters. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error * @exception ServletException for a * servlet-specified error */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); // servlet configuration initialization parameters writer.println("<h1>ServletConfig " + "Initialization Parameters</h1>"); writer.println("<ul>"); Enumeration params = getServletConfig().getInitParameterNames(); while (params.hasMoreElements()) { String param = (String) params.nextElement(); String value = getServletConfig().getInitParameter(param); writer.println("<li><b>" + param + "</b> = " + value); } writer.println("</ul>"); writer.println("<hr>"); } }
Retrieving HTTP Request Header Information
The request header is where all the details of the request are bundled. This is where the browser specifies the file wanted, date, image file support, and more. Listing 4.9 shows a popular way to display the header parameters by walking through an Enumeration of them.
Listing 4.9 Servlet That Displays the HTTP Header Information
import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /** * Displaying request headers * * @author Reader@Que */ public class DisplayRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); String title = "Requestheader Example"; out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>" + title + "</h3>"); out.println("<table>"); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String headerName = (String)e.nextElement(); String headerValue = request.getHeader(headerName); out.println("<tr><td bgcolor=\"#CCCCCC\">" + headerName); out.println("</td><td>" + headerValue + "</td></tr>"); } out.println("</table>"); out.println("</body>"); out.println("</html>"); } }
The output of this listing looks like Figure 4.4.
Figure 4.4 You can retrieve request header information using a servlet.
Acquiring a Binary Stream for the Response
Suppose you want to open a binary file in a browser from a servlet. It isn't text so you have to write the file to the servlet's output stream. Let's practice with a PDF document. First, you get the servlet's output stream with:
ServletOutputStream out = res.getOutputStream();
Next, you set the file type in the response object using one of the standard MIME (Multipurpose Internet Mail Extension) protocols. Several listings of content type names are available on the Internet including one at ftp://ftp.isi.edu/in-notes/iana/assignments/media-types. Then you use an HTTP response header named content-disposition. This header allows the servlet to specify information about the file's presentation. Using that header, you can indicate that the content should be opened separately (not actually in the browser) and that it should not be displayed automatically, but rather upon some further action by the user. You can also suggest the filename to be used if the content is to be saved to a file. That filename would be the name of the file that appears in the Save As dialog box. If you don't specify the filename, you are likely to get the name of your servlet in that box. To find out more about the content-disposition header, check out Resources or go to http://www.alternic.org/rfcs/rfc2100/rfc2183.txt.
Sending a binary stream to the client is not easy. Listing 4.10 will help you do it right.
Listing 4.10 Servlet That Sends a File to the Client
public class BinaryResponse extends HttpServlet { /**Set global variables*/ public void init(ServletConfig config) throws ServletException { super.init(config); } /**Process HTTP Post request with doPost*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = "index.html"; //set file name String contentType = getContentType(fileName); //contentType = getType(); //get the content type // get the file File file = new File(fileName); long length = file.length(); if(length > Integer.MAX_VALUE) { //handle too large file error //perhaps log and return error message to client } byte[] bytes = new byte[(long)length]; BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); // then place it into a byte array if(length != in.read(bytes)) { //handle too large file error //perhaps log and return error message to client } //get the servlet's output stream BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); //set the content type of the response response.setContentType( contentType ); //send the file to the client out.write( bytes ); } } /**Clean up resources*/ public void destroy() { //If you need to clean up resources. //Otherwise don't override. } String getContentType(String fileName) { String extension[] = { // File Extensions "txt", //0 - plain text "htm", //1 - hypertext "jpg", //2 - JPEG image "gif", //3 - gif image "pdf", //4 - adobe pdf "doc", //5 - Microsoft Word }, // you can add more mimeType[] = { // mime types "text/plain", //0 - plain text "text/html", //1 - hypertext "image/jpg", //2 - image "image/gif", //3 - image "application/pdf", //4 - Adobe pdf "application/msword", //5 - Microsoft Word }, // you can add more contentType = "text/html"; // default type // dot + file extension int dotPosition = fileName.lastIndexOf('.'); // get file extension String fileExtension = fileName.substring(dotPosition + 1); // match mime type to extension for(int index = 0; index < MT.length; index++) { if(fileExtension.equalsIgnoreCase( extension[index])) { contentType = mimeType[index]; break; } } return contentType; } }
Redirecting an HTTP Request to Another URL
It often happens that pages move around and a URL becomes invalid. Throwing back a 404 error isn't nice. The response object has the sendRedirect method, which sends a temporary redirect response to the client sending with it a new location URL. You can use relative or absolute URLs, because the Servlet Container translates a relative URL to an absolute URL before sending the response to the client.
The two potential problems with this method are sending a bad URL to the client and using this method after the response has already been committed. The bad URL will look bad, but not produce an error. The latter, though, will throw an IllegalStateException. Furthermore, after using this method, the response is committed and can't be written to, or you'll get an error. One nice feature is that this method writes a short response body including a hyperlink to the new location. This way, if the browser doesn't support redirects, it will still get the new link. Use the following syntax for this method:
// Suppose this portion of the server is down. // Redirect the user to an explanation page. redirectPath = "./error/notAvailable.html"; response.sendRedirect(redirectPath);