- 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
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\"> </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(); } }
Session
A Session is made up of multiple hits from the same browser across some period of time. The session scope includes all hits from a single machine (multiple browser windows if they share cookies). Servlets maintain state with sessions. Listing 4.13 is a modification of a sample servlet that ships with Tomcat. It demonstrates how you can use session attributes.
Listing 4.13 Servlet That Demonstrates Session Attributes
import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionExample 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("<body bgcolor=\"white\">"); out.println("<head>"); String title = "Session Servlet"; out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>" + title + "</h3>"); HttpSession session = request.getSession(); out.println("session id" + " " + session.getId()); out.println("<br/>"); out.println("session created" + " "); out.println(new Date(session.getCreationTime()) + "<br/>"); out.println("session lastaccessed" + " "); out.println( new Date(session.getLastAccessedTime())); //get these from the HTML form or query string String dataName = request.getParameter("dataname"); String dataValue =request.getParameter("datavalue"); if (dataName != null && dataValue != null) { session.setAttribute(dataName, dataValue); } out.println("<p/>"); out.println("session data" + "<br/>"); Enumeration names = session.getAttributeNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = session.getAttribute(name).toString(); out.println(name + " = " + value + "<br/>"); } out.println("<p/>"); out.print("<form action=\""); out.print(response.encodeURL("SessionExample")); out.print("\" "); out.println("method=POST>"); out.println("Name of Session Attribute:"); out.println("<input type=text size=20 " + "name=dataname>"); out.println("<br/>"); out.println("Value of Session Attribute:"); out.println("<input type=text size=20 " + "name=datavalue>"); out.println("<br/>"); out.println("<input type=submit>"); out.println("</form>"); out.println("<p/>GET based form:<br/>"); out.print("<form action=\""); out.print(response.encodeURL("SessionExample")); out.print("\" "); out.println("method=GET>"); out.println("Name of Session Attribute:"); out.println("<input type=text size=20 " + "name=dataname>"); out.println("<br/>"); out.println("Value of Session Attribute:"); out.println("<input type=text size=20 " + "name=datavalue>"); out.println("<br/>"); out.println("<input type=submit>"); out.println("</form>"); out.print("<p/><a href=\""); String url = "SessionExample?dataname=scwcd&" + "datavalue=pass!"; out.print(response.encodeURL(url)); out.println("\" >URL encoded </a>"); out.println("</body>"); out.println("</html>"); out.println("</body>"); out.println("</html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } } //returns a page that looks like: //Session Servlet // //session id 9805A5C4C084F5B47788242406C22455 //session created Tue Apr 16 22:11:06 PDT 2002 //session lastaccessed Tue Apr 16 22:13:27 PDT 2002 // //session data //publisher = Que //author = trottier //scwcd = pass!
To summarize, sessions are what you can use to track a single user over a short time. You get the session object (HttpSession) from the request object. To track multiple users over time you must jump to context, covered next.
Context
A Web application includes many parts; it rarely is just one class or one JSP. To help manage an application, you will sometimes need to set and get information that all of the servlets share together, which we say is context-wide. An example would be using a login servlet to create an application-level attribute such as application name like so:
public void init(ServletConfig config) throws ServletException { super.init(config); // set application scope parameter // to "Certification by Que" ServletContext context = config.getServletContext(); context.setAttribute( "applicationName", "Certification by Que"); }
Later, in another servlet you may use the application name as demonstrated in Listing 4.14.
Listing 4.14 Servlet doGet Method Demonstration
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<html>"); out.print("<head>"); out.print("<title>"); // get value of applicationName from ServletContext out.print(getServletContext().getAttribute( "applicationName").toString()); out.print("</title>"); out.print("<head>"); out.print("<body>"); //complete body content here... out.print("</body></html>"); out.close(); }
Besides setting and retrieving your custom attributes, you can get additional information from the Servlet Container, such as its major and minor version, the path to a given servlet, and more. The following summarizes the additional methods you might use:
getAttributeNames(). Returns an Enumeration object containing the attribute names available within this servlet context.
getContext(String uripath). Returns a ServletContext object that corresponds to a specified URL on the server.
getInitParameter(String name). Returns a string containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.
getInitParameterNames(). Returns the names of the context's initialization parameters as an Enumeration of string objects, or an empty Enumeration if the context has no initialization parameters.
getMajorVersion(). Returns the major version as an int of the Java Servlet API that this Servlet Container supports.
getMimeType(java.lang.String file). Returns the MIME type as a string of the specified file, or null if the MIME type is not known.
getMinorVersion(). Returns the minor version as an int of the Servlet API that this Servlet Container supports.
getNamedDispatcher(String name). Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
getRealPath(String path). Returns a string containing the real path for a given virtual path.
getRequestDispatcher(String path). Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
getResource(String path). Returns a URL to the resource that is mapped to a specified path.
getResourceAsStream(String path). Returns the resource located at the named path as an InputStream object.
-
getServerInfo(). Returns the name and version as a String of the Servlet Container on which the servlet is running.