Home > Articles > Programming > Java

This chapter is from the book

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); 

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020