September 16, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

The Servlet Container Model

  • October 24, 2002
  • By Que Publishing
  • Send Email »
  • More Articles »

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

Web Application Scope

This section discusses scope. There are three scopes to worry about for the exam: namely, Request, Session, and Context. Suppose you had to keep track of all your customer visits to your support Web site. Where would you place the counter? You would place it in Context scope. To better understand what I mean, please study the following objective.

1.4 Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes:

  • Request
  • Session
  • Context

This objective requires you to understand how to set and get name-value attributes at three different levels. The breadth of scope increases from Request to Session to Context, the widest scope.

Table 4.2 provides a definition of the three object scopes of concern under this objective, namely, Request, Session, and Application.

Table 4.2 Request, Session, and Application Scope

Name

Accessibility

Lifetime

Request

Current, included, or forwarded pages

Until the response is returned to the user.

Session

All requests from same browser within session timeout

Until session timeout or session ID invalidated (such as user quits browser).

application

All request to same Web application

Life of container or explicitly killed (such as container administration action).


The idea here is if you set an attribute (that is, request.setAttribute()), when can you access it? The answer depends on which object was used to the attribute. So, if you set an attribute with the request object, then the scope of that specific attribute is only Request. You can't access it once the request is complete. You can't see this attribute in another request even if it is in the same session. Conversely, any attribute set with the ServletContext object can be seen in all sessions and all requests.

Listing 4.11 is a program that demonstrates how you could use access attributes from the three primary scopes of Request, Session, and Application. You can also use setAttribute() for each of these scopes.

Listing 4.11 Attributes from Request, Session, and Application Scopes

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

public class AttributeScope extends HttpServlet {

  public void printHeader(PrintWriter out, String header) {
    out.println("  <tr>");
    out.println("  <td bgcolor=\"#999999\" " +
          "colspan=\"2\">");
    out.println("   <b>"+header+"</b>");
    out.println("  </td>");
    out.println("  </tr>");
  }

  public void printValue(PrintWriter out, String key, 
      String val) 
  {
    if (val!=null) 
    {
      if (val.length()>255) 
      val=val.substring(0,128)+" <i>(... more)</i>";
    }
    out.println("<tr>");
    out.println("<td bgcolor=\"#cccccc\">"+key+"</td>");
    out.println("<td bgcolor=\"#ffffff\">"+val+"</td>");
    out.println("</tr>");
  }

  public void printVoid(PrintWriter out) 
  {
    out.println("  <tr><td bgcolor=\"#ffffff\" " +
          "colspan=\"2\">&nbsp;</td></tr>");
  }

  public void doPost(HttpServletRequest request, 
      HttpServletResponse response)
   throws ServletException, IOException 
  {
    doGet(request,response);
  }

  public void doGet(HttpServletRequest request, 
      HttpServletResponse response)
   throws ServletException, IOException 
  {

    Enumeration enum = getInitParameterNames();
    ServletContext context = getServletContext();
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");

    out.println("<html>");
    out.println(" <head>");
    out.println(" <title>Attribute Scope Example" +
            "</title>");
    out.println(" </head>");
    out.println(" <body>");
    out.println(" <p align=center>");
    out.println("  <h2>Attribute Scope Example</h2>");

    String url=request.getScheme()+"://"+
          request.getServerName()+":"+
          request.getServerPort()+
          request.getRequestURI();

    out.println("  <table border=\"0\" cellspacing=" +
            \"2\" cellpadding=\"2\">");
    out.println("  <tr>");
    out.println("   <td>");

    out.println("   <form action=\""+url+
              "\" method=\"GET\">");
    out.println("    <input type=\"hidden\" " +
              "name=\"hiddenName\" " +
              "value=\"hiddenValue\">");
    out.println("    <input type=\"submit\" " +
              "name=\"submitName\" " +
              "value=\"Submit using GET\">");
    out.println("   </form>");

    out.println("   </td>");
    out.println("  </tr>");
    out.println("  </table>");

    out.println(" </p>");
    out.println(" <br>");

    out.println(" <table width=\"100%\" border=\"1\""+
         " cellspacing=\"0\" cellpadding=\"1\">");

    printHeader(out,"Context attributes:");
    enum = context.getAttributeNames();
    while (enum.hasMoreElements()) {
      String key = (String)enum.nextElement();
      Object val = context.getAttribute(key);
      printValue(out,key,val.toString());
    }
    printVoid(out);

    printHeader(out,"Request attributes:");
    enum = request.getAttributeNames();
    while (enum.hasMoreElements()) {
      String key = (String)enum.nextElement();
      Object val = request.getAttribute(key);
      printValue(out,key,val.toString());
    }
    printVoid(out);

    printHeader(out,"Parameter names in request:");
    enum = request.getParameterNames();
    while (enum.hasMoreElements()) {
      String key = (String)enum.nextElement();
      String[] val = request.getParameterValues(key);
      for(int i = 0; i < val.length; i++)
        printValue(out,key,val[i]);
    }
    printVoid(out);


    printHeader(out,"Session information:");
    SimpleDateFormat format = 
     new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS z");
    HttpSession session = request.getSession();
    if (session!=null) {
    printValue(out,"Requested Session Id:", 
             request.getRequestedSessionId());
      printValue(out,"Current Session Id:",
                     session.getId());
      printValue(out,"Current Time:", 
                format.format(new Date()));
      printValue(out,"Session Created Time:", 
    format.format(new Date(session.getCreationTime())));
      printValue(out,"Session Last Accessed Time:", 
  format.format(new Date(session.getLastAccessedTime())));
      printValue(out,"Session Max Inactive Interval"+
            " Seconds:", 
    Integer.toString(session.getMaxInactiveInterval()));
      printVoid(out);

      printHeader(out,"Session values:");
      enum = session.getAttributeNames();
      while (enum.hasMoreElements()) {
        String key = (String) enum.nextElement();
        Object val = session.getAttribute(key);
        printValue(out,key,val.toString());
      }
    }
    printVoid(out);

    out.println("</pre>");
    out.println("  </td>");
    out.println("  </tr>");

    out.println(" </table>");
    out.println(" </body>");
    out.println("</html>");
    out.flush();
  }
}

The output of this listing looks like Figure 4.5.

Figure 4.5
You can get attributes with Request, Session, or Application scope.

The previous listing demonstrates how to retrieve attributes from the three primary scopes. Let us now focus on the Request object.

Request

When a user hits a URL with a servlet at the other end, the Servlet Container creates an HttpServletRequest object. It passes this object as an argument to the servlet's service methods (doPut(), doGet(), and doPost()). There is a lot of information in this object, including the login of the user making this request (getRemoteUser()) and the name of the HTTP method with which this request was made (getMethod()). However, this exam objective is restricted to header information. Therefore, you need to know the following HttpServletRequest methods.

The following list of methods summarizes the Request (Interfaces: ServletRequest and HttpServletRequest) methods you need to be familiar with. While, strictly speaking, all are fair game, I marked with an asterisk those that are more likely to be on the exam:

  • *getAttribute(String name). Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

  • *getAttributeNames(). Returns an Enumeration containing the names of the attributes available to this request.

  • getAuthType(). Returns the name of the authentication scheme used to protect the servlet.

  • getCharacterEncoding(). Returns the name of the character encoding used in the body of this request.

  • getContentLength(). Returns the length, in bytes, of the request body if made available by the input stream, or -1 if the length is not known.

  • getContentType(). Returns the MIME type of the body of the request, or null if the type is not known.

  • getContextPath(). Returns the portion of the request URI that indicates the context of the request.

  • getCookies(). Returns an array containing all of the Cookie objects the client sent with this request.

  • getDateHeader(java.lang.String name). Returns the value of the specified request header as a long value that represents a Date object.

  • *getHeader(java.lang.String name). Returns the value of the specified request header as a String.

  • *getHeaderNames(). Returns an enumeration of all the header names this request contains.

  • getHeaders(java.lang.String name). Returns all the values of the specified request header as an Enumeration of String objects.

  • getInputStream(). Retrieves the body of the request as binary data using a ServletInputStream.

  • getIntHeader(java.lang.String name). Returns the value of the specified request header as an int.

  • getLocale(). Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

  • getLocales(). Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header.

  • *getMethod(). Returns the name of the HTTP method with which this request was made; for example, GET, POST, or PUT.

  • *getParameter(java.lang.String name). Returns the value of a request parameter as a string, or null if the parameter does not exist.

  • getParameterMap(). Returns a java.util.Map of the parameters of this request.

  • *getParameterNames(). Returns an Enumeration of string objects containing the names of the parameters contained in this request.

  • *getParameterValues(java.lang.String name). Returns an array of string objects containing all of the values the given request parameter has, or null if the parameter does not exist.

  • getPathInfo(). Returns any extra path information associated with the URL the client sent when it made this request.

  • getPathTranslated(). Returns any extra path information after the servlet name but before the query string, and translates it to a real path.

  • getProtocol(). Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1.

  • *getQueryString(). Returns the query string that is contained in the request URL after the path.

  • getReader(). Retrieves the body of the request as character data using a BufferedReader.

  • getRemoteAddr(). Returns the Internet Protocol (IP) address of the client that sent the request.

  • getRemoteHost(). Returns the fully qualified name of the client that sent the request.

  • getRemoteUser(). Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

  • *getRequestDispatcher(java.lang.String path). Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

  • getRequestURI(). Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.

  • getRequestURL(). Reconstructs the URL the client used to make the request.

  • getRequestedSessionId(). Returns the session ID specified by the client.

  • getScheme(). Returns the name of the scheme used to make this request; for example, http, https, or ftp.

  • getServerName(). Returns the host name of the server that received the request.

  • getServerPort(). Returns the port number on which this request was received.

  • getServletPath(). Returns the part of this request's URL that calls the servlet.

  • *getSession(). Returns the current session (HttpSession) associated with this request, or if the request does not have a session, creates one.

  • *getSession(boolean create). Returns the current HttpSession associated with this request, or, if there is no current session and create is true, returns a new session.

  • getUserPrincipal(). Returns a java.security.Principal object containing the name of the current authenticated user.

  • isRequestedSessionIdFromCookie(). Checks whether the requested session ID came in as a cookie.

  • isRequestedSessionIdFromURL(). Checks whether the requested session ID came in as part of the request URL.

  • isRequestedSessionIdValid(). Checks whether the requested session ID is still valid.

  • isSecure(). Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

  • isUserInRole(java.lang.String role). Returns a boolean indicating whether the authenticated user is included in the specified logical "role".

  • *removeAttribute(java.lang.String name). Removes an attribute from this request.

  • *setAttribute(java.lang.String name, java.lang.Object o). Stores an attribute in this request.

  • setCharacterEncoding(java.lang.String env). Overrides the name of the character encoding used in the body of this request.

Several of the HttpServletRequest methods are not mentioned specifically in the objectives, but you should be familiar with them. Listing 4.11 is a program that demonstrates how you would retrieve attributes from the Request object, the main concern in the current exam objective. However, I thought you might also like to see what else you can do with this object. Listing 4.12 uses the Request object's methods to retrieve HTTP request header information (similar to Listing 4.10). Of course, the information you get out of the Request object has only Request scope.

Listing 4.12 Servlet That Retrieves Request Header Information

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * set request attributes
 *
 * @author Reader@Que
 */

public class RequestDislay extends HttpServlet 
{
  public void doGet(HttpServletRequest request,
           HttpServletResponse response)
    throws IOException, ServletException
  {

  // Set MIME type response header
  response.setContentType("text/html");

  // Acquire a text stream for the response
  PrintWriter out = response.getWriter();

  //prefer to buffer html then print all at once
  StringBuffer html = new StringBuffer();

  // HTML header
  html.append("<html>");
  html.append("<head>");
  html.append("<title>");
  html.append("Servlet Header Example");
  html.append("</title>");
  html.append("<head>");
  html.append("<body>");

  // begin the HTML body
  html.append("<h1>Request info</h1>");

  // build list of header name-value pairs
  String headerName;
  String headerValue;
  Enumeration headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) 
  {
   //enumeration returns object so cast as String
   headerName = (String) headerNames.nextElement();
   headerValue = request.getHeader(headerName);
   html.append(" " + headerName + " : " + headerValue +
         "<br/>");
  }

  //These methods are not named by objectives, but are
  // good to know. 
  //A simple march down the API:
  html.append("Auth Type: " + request.getAuthType());
  html.append("Character Encoding: " + 
              request.getCharacterEncoding());
  html.append("Content Length: " + 
                request.getContentLength());
  html.append("Content Type: "+ request.getContentType());
  html.append("Method: " + request.getMethod());
  html.append("Path Info: " + request.getPathInfo());
  html.append("Path Translated: " + 
                request.getPathTranslated());
  html.append("Protocol: " + request.getProtocol());
  html.append("Query String: " + request.getQueryString());
  html.append("Remote Address: "+ request.getRemoteAddr());
  html.append("Remote Host: " + request.getRemoteHost());
  html.append("Request URI: " + request.getRequestURI());
  html.append("Remote User: " + request.getRemoteUser());
  html.append("Scheme: " + request.getScheme());
  html.append("Server Name: " + request.getServerName());
  html.append("Servlet Path: " + request.getServletPath());
  html.append("Server Port: " + request.getServerPort());

  // build list of parameter name-value pairs
  html.append("Parameters:");
  Enumeration parameterNames =request.getParameterNames();
  while (parameterNames.hasMoreElements()) 
  {
   String parameterName = 
           (String) parameterNames.nextElement();
   String[] parameterValues = 
         request.getParameterValues(parameterName);
   html.append("  " + parameterName + ":");
   for (int i = 0; i < parameterValues.length; i++) 
   {
     html.append("   " + parameterValues[i]);
   }
  }

  // build list of cookie name-value pairs
  html.append("Cookies:");
  Cookie[] cookies = request.getCookies();
  for (int i = 0; i < cookies.length; i++) 
  {
   String cookieName = cookies[i].getName();
   String cookieValue = cookies[i].getValue();
   html.append(" " + cookieName + " : " + cookieValue);
  }
  html.append("</body>");
  html.append("</html>");

  // optional use descriptive elements to clarify code
  final String BEGIN_TAG = "<";
  final String CLOSE_TAG = "/";
  final String END_TAG = ">";

  // Print the HTML footer
  html.append(BEGIN_TAG + CLOSE_TAG + "body" + END_TAG);
  html.append(BEGIN_TAG + CLOSE_TAG + "html" + END_TAG);

  // Sometimes it is better (performance improvement) 
  // to send html to stream all at once.
  out.print( html );
  out.close();
 }
}




Page 3 of 5



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel