16.5 Accessing Scoped Variables

16.5 Accessing Scoped Variables

When you use the MVC approach (Chapter 15), a servlet invokes code that creates the data, then uses RequestDispatcher.forward or response.sendRedirect to transfer control to the appropriate JSP page. To permit the JSP page to access the data, the servlet needs to use setAttribute to store the data in one of the standard locations: the HttpServletRequest , the HttpSession , or the ServletContext .

Objects in these locations are known as "scoped variables," and the expression language has a quick and easy way to access them. You can also have scoped variables stored in the PageContext object, but this is much less useful because the servlet and the JSP page do not share PageContext objects. So, page-scoped variables apply only to objects stored earlier in the same JSP page, not to objects stored by a servlet.

To output a scoped variable, you simply use its name in an expression language element. For example,

 
 ${name} 

means to search the PageContext , HttpServletRequest , HttpSession , and ServletContext (in that order) for an attribute named name . If the attribute is found, its toString method is called and that result is returned. If nothing is found, an empty string (not null or an error message) is returned. So, for example, the following two expressions are equivalent.

 
 ${name} <%= pageContext.findAttribute("name") %> 

The problems with the latter approach are that it is verbose and it requires explicit Java syntax. It is possible to eliminate the Java syntax, but doing so requires the following even more verbose jsp:useBean code.

 
 <jsp:useBean id="name" type="  somePackage.SomeClass  " scope="..."> <%= name %> 

Besides, with jsp:useBean , you have to know which scope the servlet used, and you have to know the fully qualified class name of the attribute. This is a significant inconvenience, especially when the JSP page author is someone other than the servlet author.

Choosing Attribute Names

To use the JSP expression language to access scoped variables, you must choose attribute names that would be legal as Java variable names. So, avoid dots, spaces, dashes, and other characters that are permitted in strings but forbidden in variable names.

Also, you should avoid using attribute names that conflict with any of the predefined names given in Section 16.8.

An Example

To illustrate access to scoped variables, the ScopedVars servlet (Listing 16.1) stores a String in the HttpServletRequest , another String in the HttpSession , and a Date in the ServletContext . The servlet forwards the request to a JSP page (Listing 16.2, Figure 16-2) that uses ${ attributeName } to access and output the objects.

Figure 16-2. The JSP 2.0 expression language simplifies access to scoped variables: objects stored as attributes of the page, request, session, or servlet context.

graphics/16fig02.jpg

Notice that the JSP page uses the same syntax to access the attributes, regardless of the scope in which they were stored. This is usually a convenient feature because MVC servlets almost always use unique attribute names for the objects they store. However, it is technically possible for attribute names to be repeated, so you should be aware that the expression language searches the PageContext , HttpServletRequest , HttpSession , and ServletContext in that order . To illustrate this, the servlet stores an object in each of the three shared scopes, using the attribute name repeated in all three cases. The value returned by ${repeated} (see Figure 16-2) is the first attribute found when searching the scopes in the defined order (i.e., the HttpServletRequest in this case). Refer to Section 16.8 (Referencing Implicit Objects) if you want to restrict the search to a particular scope.

Listing 16.1 ScopedVars.java
 package coreservlets; /** Servlet that creates some scoped variables (objects stored  *  as attributes in one of the standard locations). Forwards  *  to a JSP page that uses the expression language to  *  display the values.  */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ScopedVars extends HttpServlet {   public void doGet(HttpServletRequest request,                     HttpServletResponse response)       throws ServletException, IOException {  request.setAttribute("attribute1", "First Value");  HttpSession session = request.getSession();  session.setAttribute("attribute2", "Second Value");  ServletContext application = getServletContext();  application.setAttribute("attribute3",   new java.util.Date());   request.setAttribute("repeated", "Request");   session.setAttribute("repeated", "Session");   application.setAttribute("repeated", "ServletContext");  RequestDispatcher dispatcher =       request.getRequestDispatcher("/el/scoped-vars.jsp");     dispatcher.forward(request, response);   } } 
Listing 16.2 scoped-vars.jsp
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Accessing Scoped Variables</TITLE> <LINK REL=STYLESHEET       HREF="/el/JSP-Styles.css"       TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER">   <TR><TH CLASS="TITLE">   Accessing Scoped Variables </TABLE> <P> <UL>   <LI><B>attribute1:</B>  ${attribute1}  <LI><B>attribute2:</B>  ${attribute2}  <LI><B>attribute3:</B>  ${attribute3}  <LI><B>Source of "repeated" attribute:</B>  ${repeated}  </UL> </BODY></HTML> 


Core Servlets and JavaServer Pages (Vol. 1.Core Technologies)
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)
ISBN: 0130092290
EAN: 2147483647
Year: 2002
Pages: 194

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net