Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
356
Chapter 15 Integrating Servlets and JSP
information it needs out of the 
HttpServletRequest
. There are two reasons
why it might not be a good idea to have the destination page look up and pro 
cess all the data itself. First, complicated programming is easier in a servlet
than in a JSP page. Second, multiple JSP pages may require the same data, so
it would be wasteful for each JSP page to have to set up the same data. A bet 
ter approach is for the original servlet to set up the information that the desti 
nation pages need, then store it somewhere that the destination pages can
easily access.
There are two main places for the servlet to store the data that the JSP pages
will use: in the 
HttpServletRequest
 and as a bean in the location specific to
the 
scope
 attribute of 
jsp:useBean
 (see Section 13.4,  Sharing Beans  ).
The originating servlet would store arbitrary objects in the 
HttpServlet 
Request
 by using 
request.setAttribute("key1", value1);
The destination page would access the value by using a JSP scripting ele 
ment to call 
Type1 value1 = (Type1)request.getAttribute("key1");
For complex values, an even better approach is to represent the value as a
bean and store it in the location used by 
jsp:useBean
 for shared beans. For
example, a 
scope
 of 
application
 means that the value is stored in the
ServletContext
, and 
ServletContext
 uses 
setAttribute
 to store values.
Thus, to make a bean accessible to all servlets or JSP pages in the server or
Web application, the originating servlet would do the following:
Type1 value1 = computeValueFromRequest(request);
getServletContext().setAttribute("key1", value1);
The destination JSP page would normally access the previously stored
value by using 
jsp:useBean
 as follows:
Alternatively, the destination page could use a scripting element to explic 
itly call 
application.getAttribute("key1")
 and cast the result to 
Type1
.
For a servlet to make data specific to a user session rather than globally
accessible, the servlet would store the value in the 
HttpSession
 in the nor 
mal manner, as below:
Type1 value1 = computeValueFromRequest(request);
HttpSession session = request.getSession(true);
session.putValue("key1", value1);
The destination page would then access the value by means of
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved