Arguably, the most useful feature of the JSTL expression language is the implicit objects it defines for accessing all kinds of application data. Those implicit objects are listed in Table 2.5. Table 2.5. JSTL Implicit Objects
There are three types of JSTL implicit objects:
The rest of this section examines each of the JSTL implicit objects in the order listed above; the first category begins at "Accessing Request Parameters" below, the second category begins at "Accessing Scoped Attributes" on page 78, and use of the pageContext implicit object begins at "Accessing JSP Page and Servlet Properties" on page 80. Accessing Request ParametersRequest parameters are the lifeblood of most Web applications, passing information from one Web component to another. That crucial role makes the param and paramValues implicit objects, both of which access request parameters, the most heavily used JSTL implicit objects. The param and paramValues implicit objects are both maps of request parameters. For both the param and paramValues maps, keys are request parameter names , but the values corresponding to those keys are different for param and paramValues ; param stores the first value specified for a request parameter, whereas paramValues stores a String array that contains all the values specified for a request parameter. [11]
Most often, the overriding factor that determines whether you use param or paramValue is the type of HTML element a request parameter represents; for example, Figure 2-5 shows a Web application that uses both param and paramValues to display request parameters defined by a form. Figure 2-5. Accessing Request Parameters with the param and paramValues Implicit Objects
The Web application shown in Figure 2-5 consists of two JSP pages, one that contains a form (top picture) and another that interprets the form's data (bottom picture). Listing 2.13 lists the JSP page that contains the form. Listing 2.13 index.jsp<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>EL Implicit Objects: Request Parameters</title> </head> <body> <form action='param.jsp'> <table> <tr> <td>First Name:</td> <td><input type='text' name='firstName'/></td> </tr> <tr> <td>Last Name:</td> <td><input type='text' name='lastName'/></td> </tr> <tr> <td> Select languages that you have worked with: </td> <td> <select name='languages' size='7' multiple='true'> <option value='Ada'>Ada</option> <option value='C'>C</option> <option value='C++'>C++</option> <option value='Cobol'>Cobol</option> <option value='Eiffel'>Eiffel</option> <option value='Objective-C'> Objective-C </option> <option value='Java'>Java</option> </select> </td> </tr> </table> <p><input type='submit' value='Finish Survey'/> </form> </body> </html> The preceding JSP page is unremarkable; it creates an HTML form with two textfields and a select element that allows multiple selection. That form's action, param.jsp , is the focus of our discussion. It is listed in Listing 2.14. Listing 2.14 param.jsp<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Accessing Request Parameters</title> </head> <body> <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %> <font size='5'> Skillset for: </font> <%-- Access the lastName and firstName request parameters parameters by name --%> <c:out value='${param.lastName}'/>, <c:out value='${param.firstName}'/> <%-- Show all request parameters and their values --%> <p><font size='5'> All Request Parameters: </font><p> <%-- For every String[] item of paramValues... --%> <c:forEach var='parameter' items=' ${paramValues} '> <ul> <%-- Show the key, which is the request parameter name --%> <li><b><c:out value=' ${parameter.key} '/></b>:</li> <%-- Iterate over the values -- a String[] -- associated with this request parameter --%> <c:forEach var='value' items=' ${parameter.value} '> <%-- Show the String value --%> <c:out value='${value}'/> </c:forEach> </ul> </c:forEach> <%-- Show values for the languages request parameter --%> <font size='5'> Languages: </font><p> <%-- paramValues.languages is a String [] of values for the languages request parameter --%> <c:forEach var='language' items=' ${paramValues.languages} '> <c:out value='${language}'/> </c:forEach> <p> <%-- Show the value of the param.languages map entry, which is the first value for the languages request parameter --%> <c:out value=" ${'${'}param.languages} = ${param.languages} "/> </body> </html> The preceding JSP page does four things of interest. First, it displays the lastName and firstName request parameters, using the param implicit object. Since we know that those request parameters represent textfields, we know that they are a single value, so the param implicit object fits the bill. Second, the JSP page displays all of the request parameters and their values, using the paramValues implicit object and the <c:forEach> action. [12] We use the paramValues implicit object for this task since we know that the HTML select element supports multiple selection and so can produce multiple request parameter values of the same name.
Because the paramValues implicit object is a map, you can access its values directly if you know the keys, meaning the request parameter names. For example, the third point of interest in the preceding JSP page iterates over the array of strings representing selected languages ” paramValues.languages . The selected languages are accessed through the paramValues map by use of the key languages . To emphasize the difference between param and paramValues , the fourth point of interest is the value of the param.languages request parameter, which contains only the first language selected in the HTML select element. A <c:out> action uses the EL expression ${'${'} to display the characters ${ and another EL expression ” ${param.languages} ”to display the first value for the languages request parameter. Accessing Request HeadersYou can access request headers just as you can access request parameters, except that you use the header and headerValues implicit objects instead of param and paramValues . Like the param and paramValues implicit objects, the header and headerValues implicit objects are maps, but their keys are request header names. The header map's values are the first value specified for a particular request header, whereas the headerValues map contains arrays of all the values specified for that request header. Figure 2-6 shows a JSP page that uses the header implicit object to display all of the request headers and the first value defined for each of them. Figure 2-6. Accessing Request Headers with the header Implicit Object
The JSP page shown in Figure 2-6 is listed in Listing 2.15. The keys stored in the header map are request header names and the corresponding values are strings representing request header values. You can also use the headerValues implicit object to iterate over request headers, like this: <%-- Loop over the JSTL headerValues implicit object, which is a map --%> <c:forEach items=' ${headerValues} ' var='hv'> <ul> <%-- Display the key of the current item; that item is a Map.Entry --%> <li>Header name: <c:out value=' ${hv.key} '/></li> <%-- The value of the current item, which is accessed with the value method from Map.Entry, is an array of strings representing request header values, so we iterate over that array of strings --%> <c:forEach items=' ${hv.value} ' var='value'> <li>Header Value: <c:out value='${value}'/></li> </c:forEach> </ul> </c:forEach> Listing 2.15 Accessing Requests Headers with the header Implicit Object<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Request Headers</title> </head> <body> <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %> <font size='5'> Request Headers: </font><p> <%-- Loop over the JSTL header implicit object, which is a map --%> <c:forEach items=' ${header} ' var='h'> <ul> <%-- Display the key of the current item, which represents the request header name and the current item's value, which represents the header value --%> <li>Header Name: <c:out value=' ${h.key} '/></li> <li>Header Value: <c:out value=' ${h.value} '/></li> </ul> </c:forEach> </body> </html> Unlike request parameters, request headers are rarely duplicated; instead, if multiple strings are specified for a single request header, browsers typically concatenate those strings separated by semicolons. Because of the sparsity of duplicated request headers, the header implicit object is usually preferred over headerValues . Accessing Context Initialization ParametersYou can have only one value per context initialization parameter, so there's only one JSTL implicit object for accessing initialization parameters: initParam . Like the implicit objects for request parameters and headers, the initParam implicit object is a map. The map keys are context initialization parameter names and the corresponding values are the context initialization parameter values. Figure 2-7 shows a JSP page that iterates over all the context initialization parameters and prints their values. That JSP page also accesses the parameters directly. Figure 2-7. Accessing Initialization Parameters with the initParam Implicit Object
Before we discuss the listing for the JSP page shown in Figure 2-7, let's look at the deployment descriptor, listed in Listing 2.16, which defines two context initialization parameters: com.acme. invaders .difficulty and com.acme.invaders. gameLevels . The context initialization parameters defined above are accessed by the JSP page shown in Figure 2-7 and listed in Listing 2.17. The preceding JSP page uses the <c:forEach> action to iterate over the key/value pairs stored in the initParam map. The body of that action displays each key/value pair. In the example discussed in "Accessing Request Parameters" on page 65, we accessed a request parameter by name like this: ${paramValues. languages} . In the preceding JSP page, can we access an initialization parameter in a similar fashion with the initParam implicit object? The answer is yes, but in this case we have a problem because the initialization parameter name has . characters, which have special meaning to the expression language. If we try to access the com.acme.invaders.difficulty parameter like this: ${initParam.com.acme.invaders.difficulty} , the expression language will interpret that expression as an object's property named difficulty , which is not the interpretation we want. Listing 2.16 WEB-INF/web.xml<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd"> <web-app> <!-- Application-wide default values for the Acme Invaders online game --> <context-param> <param-name> com.acme.invaders.difficulty </param-name> <param-value> 18 </param-value> </context-param> <context-param> <param-name> com.acme.invaders.gameLevels </param-name> <param-value> 33 </param-value> </context-param> <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app> Listing 2.17 Accessing Context Initialization Parameters<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Context Initialization Parameters</title> </head> <body> <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %> <font size='5'> Iterating Over Context Initialization Parameters: </font><p> <%-- Loop over the JSTL initParam implicit object, which is a map --%> <c:forEach items=' ${initParam} ' var='parameter'> <ul> <%-- Display the key of the current item, which corresponds to the name of the init param --%> <li>Name: <c:out value=' ${parameter.key} '/></li> <%-- Display the value of the current item, which corresponds to the value of the init param --%> <li>Value: <c:out value=' ${parameter.value} '/></li> </ul> </c:forEach> <font size='5'> Accessing Context Initialization Parameters Directly: </font><p> Difficulty: <c:out value=' ${initParam["com.acme.invaders.difficulty"]} '/> Game Levels: <c:out value=' ${initParam["com.acme.invaders.gameLevels"]} '/> </body> </html> The solution to this difficulty is to use the [] operator, which evaluates an expression and turns it into an identifier; for example, you can access the com.acme.invaders.difficulty initialization parameter like this: ${initParam["com.acme.invaders.difficulty"]} . See "A Closer Look at the [] Operator" on page 56 for more information about the [] operator. Accessing CookiesIt's not uncommon to read cookies in JSP pages, especially cookies that store user -interface - related preferences. The JSTL expression language lets you access cookies with the cookie implicit object. Like all JSTL implicit objects, the cookie implicit object is a map. [13] That map's keys represent cookie names, and the values are the cookies themselves .
Figure 2-8 shows a JSP page that reads cookie values, using the cookie implicit object. Figure 2-8. Accessing Cookies with the cookie Implicit Object
The JSP page shown in Figure 2-8 uses the cookie implicit object to iterate over all cookies and also accesses Cookie objects and their values directly. That JSP page is invoked with the URL /cookieCreator , which is mapped to a servlet that creates cookies. That servlet, after creating cookies, forwards to the JSP page shown in Figure 2-8. Listing 2.18 lists the Web application's deployment descriptor, which maps the URL /cookieCreator to the CookieCreatorServlet class. Listing 2.18 WEB-INF/web.xml<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd"> <web-app> <servlet> <servlet-name>cookieCreator</servlet-name> <servlet-class>CookieCreatorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>cookieCreator</servlet-name> <url-pattern>/cookieCreator</url-pattern> </servlet-mapping> </web-app> The CookieCreatorServlet class is listed in Listing 2.19. Listing 2.19 WEB-INF/classes/CookieCreatorServlet.javaimport java.io.IOException; import javax.servlet.*; import javax.servlet.http.*; public class CookieCreatorServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String[] cookieNames = {"acme.userName", "acme.password", "acme.lastAccessDate"}; String[] cookieValues = {"ronw", "iuo82wer", "2002-03-08"}; // Create cookies and add them to the HTTP response for(int i=0; i < cookieNames.length; ++i) { Cookie cookie = new Cookie(cookieNames[i], cookieValues[i]); response.addCookie(cookie); } // Forward the request and response to cookies.jsp RequestDispatcher rd = request.getRequestDispatcher("cookies.jsp"); rd.forward(request, response); } } The cookie creator servlet creates three cookies and adds them to the response before forwarding to cookies.jsp . That JSP page is listed in Listing 2.20. Listing 2.20 cookies.jsp<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Cookies</title> </head> <body> <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %> <p><font size='5'> Iterating over Cookies: </font><p> <%-- Loop over the JSTL cookie implicit object, which is a map. If there are no cookies, the <c:forEach> action does nothing. --%> <c:forEach items=' ${cookie} ' var='mapEntry'> <ul> <%-- The mapEntry's key references the cookie name --%> <li>Cookie Name: <c:out value=' ${mapEntry.key} '/></li> <%-- The mapEntry's value references the Cookie object, so we show the cookie's value --%> <li>Cookie Value: <c:out value=' ${mapEntry.value.value} '/></li> </ul> </c:forEach> <p><font size='5'> Accessing Cookies Directly: </font><p> Cookie Objects: <ul> <li> User Name: <c:out value=' ${cookie["acme.userName"]} '/> </li> <li> Password: <c:out value=' ${cookie["acme.password"]} '/> </li> </ul> Cookie Values: <ul> <li> User Name: <c:out value=' ${cookie["acme.userName"].value} '/> </li> <li> Password: <c:out value=' ${cookie["acme.password"].value} '/> </li> </ul> </body> </html> The preceding JSP page uses the <c:forEach> action to iterate over the entries contained in the cookie map. For each entry, the body of the <c:forEach> action displays the cookie's name and value. Notice that cookie values are accessed with the expression ${mapEntry.value.value} . The map entry's value is a cookie, which also has a value property. The rest of the JSP page accesses cookie objects and their values directly. Because the cookie names contain . characters, they cannot be used as identifiers, so the preceding JSP page uses the [] operator to directly access cookies and their values. Accessing Scoped AttributesSince we started discussing JSTL implicit objects at "Implicit Objects" on page 64, we've seen how to access four types of objects:
In addition to the specific types listed above, you can access any type of object that's stored in one of the four JSP scopes: page, request, session, or application. The expression language provides one implicit object for each scope:
Remember from our discussion in "Identifiers" on page 43 that identifiers refer to scoped variables; for example, the expression ${name} refers to a scoped variable named name . That scoped variable can reside in page, request, session, or application scope. The expression language searches those scopes, in that order, for scoped variables. The implicit objects listed above let you explicitly access variables stored in a specific scope; for example, if you know that the name scoped variable resides in session scope, the expression ${sessionScope.name} is equivalent to ${name} , but the latter unnecessarily searches the page and request scopes before finding the name scoped variable in session scope. Because of that unnecessary searching, ${sessionScope.name} should be faster than ${name} . The scope implicit objects listed above ” pageScope , requestScope , sessionScope , and applicationScope ”are also handy if you need to iterate over attributes stored in a particular scope; for example, you might look for a timestamp attribute in session scope. The scope implicit objects give you access to a map of attributes for a particular scope. Figure 2-9 shows a Web application that displays all of the attributes from the scope of your choosing. The top picture in Figure 2-9 shows a JSP page that lets you select a scope, and the bottom picture shows a JSP page that lists the attributes for the selected scope. Figure 2-9. Accessing Scoped Variables for a Specific Scope with the pageScope Implicit Object
The JSP page shown in the top picture in Figure 2-9 is listed in Listing 2.21. Listing 2.21 Choosing a Scope<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Select a Scope</title> </head> <body> <form action='show_scope_attributes.jsp'> Select a scope: <select name='scope'> <option value='page'>page</option> <option value='request'>request</option> <option value='session'>session</option> <option value='application'>application</option> </select> <p><input type='submit' value='Show Scope Attributes'/> </form> </body> </html> The preceding JSP page creates an HTML form that lets you select a scope. That form's action is show_scope_attributes.jsp , which is listed in Listing 2.22. The preceding JSP page is passed a request parameter named scope whose value is "page" , "request" , "session" , or "application" . The JSP page creates a page-scoped variable, also named scope , and sets it to the appropriate JSTL implicit object ” pageScope , requestScope , sessionScope , or applicationScope ”based on the scope request parameter. Then the JSP page loops over that implicit object and displays each scoped variable's name and value. Accessing JSP Page and Servlet PropertiesNow that we've seen how to access request parameters and headers, initialization parameters, cookies, and scoped variables, the JSTL implicit objects have one more feature to explore: accessing servlet and JSP properties, such as a request's protocol or server port, or the major and minor versions of the servlet API your container supports. You can find out that information and much more with the pageContext implicit object, which gives you access to the request, response, session, and application (also known as the servlet context). Useful properties for the pageContext implicit object are listed in Table 2.6. Listing 2.22 Showing Scoped Variables for a Specific Scope<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Scoped Variables</title> </head> <body> <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %> <%-- Set a page-scoped attribute named scope to pageScope, requestScope, sessionScope, or applicationScope, depending on the value of a request parameter named scope --%> <c:choose> <c:when test='${param.scope == "page"}'> <c:set var='scope' value='${pageScope}'/> </c:when> <c:when test='${param.scope == "request"}'> <c:set var='scope' value='${requestScope}'/> </c:when> <c:when test='${param.scope == "session"}'> <c:set var='scope' value='${sessionScope}'/> </c:when> <c:when test='${param.scope == "application"}'> <c:set var='scope' value='${applicationScope}'/> </c:when> </c:choose> <font size='5'> <c:out value='${param.scope}'/>-scope attributes: </font><p> <%-- Loop over the JSTL implicit object, stored in the page-scoped attribute named scope that was set above. That implicit object is a map --%> <c:forEach items=' ${scope} ' var='p'> <ul> <%-- Display the key of the current item, which represents the parameter name --%> <li>Parameter Name: <c:out value=' ${p.key} '/></li> <%-- Display the value of the current item, which represents the parameter value --%> <li>Parameter Value: <c:out value=' ${p.value} '/></li> </ul> </c:forEach> </body> </html> Table 2.6. pageContext Properties
The pageContext properties listed in Table 2.6 give you access to a lot of information; for example, you can access a client's host name like this: ${pageContext.request.remoteHost} , or you can access the session ID like this: ${pageContext.session.id} . The following four tables list useful request, response, session, and application properties, all of which are available through the pageContext implicit object. Table 2.7. pageContext.request Properties
Table 2.8. pageContext.response Properties
Table 2.9. pageContext.session Properties
Table 2.10. pageContext.servletContext Properties
The JSP page shown in Figure 2-10 accesses some of the information available in the preceding tables: the request port, protocol, and locale; the response locale; the session ID and maximum inactive interval; and the servlet API version supported by the JSP container. Figure 2-10. Using the pageContext Implicit Object
The JSP page shown in Figure 2-10 is listed in Listing 2.23. Listing 2.23 Accessing Servlet and JSP Properties<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Using the pageContext Implicit Object</title> </head> <body> <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %> <%-- Show Request Information --%> <font size='5'>Request Information</font><p> <%-- Use the request object to show the server port and protocol --%> The current request was made on <b>port <c:out value=' ${pageContext.request.serverPort} '/></b> with this <b>protocol: <c:out value=' ${pageContext.request.protocol} '/></b>.<br> <%-- Use the request object to show the user's preferred locale --%> The request <b>locale</b> is <b><c:out value=' ${pageContext.request.locale} '/>.</b> <p> <%-- Show Response Information --%> <font size='5'>Response Information</font><p> The response <b>locale</b> is <b><c:out value=' ${pageContext.response.locale} '/>.</b> <%-- Use the response object to show whether the response has been committed --%> The <b>response <c:choose> <c:when test=' ${pageContext.response.committed} '> has </c:when> <c:otherwise> has not </c:otherwise> </c:choose> </b> been committed. <p> <%-- Show Session Information --%> <font size='5'>Session Information</font><p> Session ID: <b><c:out value=' ${pageContext.session.id} '/></b><br> Max Session Inactive Interval:<b> <c:out value=' ${pageContext.session.maxInactiveInterval} '/> </b>seconds. <p> <%-- Show Application Information --%> <font size='5'>Application Information</font><p> <%-- Store the servlet context in a page-scoped variable named app for better readability --%> <c:set var='app' value=' ${pageContext.servletContext} '/> <%-- Use the application object to show the major and minor versions of the servlet API that the container supports --%> Your servlet container supports version<b> <c:out value=' ${app.majorVersion}.${app.minorVersion} '/></b> of the servlet API. </body> </html> The preceding JSP page accesses request, response, session, and application properties, using the pageContext implicit object. The end of that JSP page creates a page-scoped variable named app that references the servlet context (meaning the application). That page-scoped variable is subsequently used to access the Servlet API version supported by the JSP container. Sometimes it's convenient , for the sake of readability, to store a reference to one of the objects listed in Table 2.6 on page 82 in a page-scoped variable, as does the preceding JSP page. |