IBM Skip to main content
Search for:   within 
      Search help  
     IBM home  |  Products & services  |  Support & downloads   |  My account

developerWorks > Java technology
developerWorks
JSP best practices: Combine JavaBeans components and JSP technology
69 KBe-mail it!
Contents:
A JavaBean component for storing data
Passing stored data
Receiving data
Managing change
Till next time
Resources
About the author
Rate this article
Related content:
JSP best practices series
EJB best practices series
Developing portlets that use JavaBeans and JSP components
A JSTL primer
Subscriptions:
dW newsletters
dW Subscription
(CDs and downloads)
Use JavaBeans and JSP parameters to pass data around your Web pages

Level: Introductory

Brett McLaughlin (mailto:brett@oreilly.com?cc=&subject=Combine JavaBeans components and JSP technology)
Author, O'Reilly and Associates
13 May 2003

Column iconWeb architect Brett McLaughlin demonstrates how combining JavaBeans components and JSP technology lets you store and pass data between your Web pages, and how doing so leads to more dynamic site design.

So far in the JSP best practices series we've focused on rather elementary topics. In the previous two installments, you learned how to use the JSP include mechanism to pull in outside content for your Web site or Web application. We used two different types of include directive: the static include command and the dynamic jsp:include tag.

Up until now, there has been no need to create any kind of communication between the parent page (a Web site main page in our example) and included content. But this scenario is overly simplistic. When it comes to programming a real Web site or Web application interface, you will generally require a communication mechanism to pass data between the parent page and included files. For example, your Web site might have a title or message that originates in the main page and needs to be supplied to a header or footer page. In this installment, you'll learn how to pass data from one page to another, and then how to use that data in included pages.

Note: All of the best practices in this series are based on JavaServer Pages technology. To run any of them, you'll need to set up a JSP technology-compliant Web container, either on your local machine or on a test server. You'll also need to use a text editor or IDE to code your JSP pages.

A JavaBean component for storing data
Let's consider a Web site where each page has a short "slogan" (such as "Books: A shelf full of learning" or "CDs: Music worth listening to") and a title. The parent page (sometimes called a master page) determines the slogan for each page, but the header, an included page, deals with the HTML to output that slogan. To make this scenario work, the master page has to be able to pass the slogan into the header, and the header has to be able to accept a page title and display it on request.

The first thing we need is some sort of object to store the data being passed around. It just so happens (not by accident) that JavaBeans components are both suitable for this purpose and a perfect match for JSP technology. The bean simply needs to have accessor and mutator methods to handle the data. As you may know from your other Java programming experience, get() is an accessor method, because it accesses data, and set() is a mutator method, because it mutates, or changes, data.

Listing 1 shows the code for the type of bean that we need. The PageHeaderInfo bean contains information about the page header for a Web site.

Listing 1. The PageHeaderInfo JavaBean

<![CDATA[
package com.newInstance.site.beans;

import java.io.Serializable;

public class PageHeaderInfo implements Serializable {

     /** The title of the page */
     private String pageTitle;

     /** The slogan of the page */
     private String pageSlogan;

     public String getPageTitle() {
       return pageTitle;
     }

     public void setPageTitle(String pageTitle) {
       this.pageTitle = pageTitle;
     }

     public String getPageSlogan() {
       return pageSlogan;
     }

     public void setPageSlogan(String pageSlogan) {
       this.pageSlogan = pageSlogan;
     }
}
]]>

For our first exercise, save this file as PageHeaderInfo.java and then compile it. Next, put the resultant class file, PageHeaderInfo.class, into your Web application's WEB-INF/classes directory. Be sure to include the package hierarchy, but feel free to change the package name. An example path to this compiled class is:


$<TOMCAT-ROOT>/webapps/$<WEB-APP-NAME>/WEB-INF/classes/com/newInstance/
  site/beans/PageHeaderInfo.class

You can use a path like this to make the class available to servlets, JSP pages, and other classes in your Web application. If you've followed the steps so far, you're now ready to populate the data in the PageHeaderInfo bean and then retrieve it in your various JSP pages.

Passing stored data
In our Web site scenario, the page header contains the code to pass various slogans to different pages. As you'll recall from the previous installment, the header (header.jsp) is an included file, managed by the jsp:include element. Because we've used the dynamic jsp:include tag, and not the static include directive, passing data into the header is easy. The jsp:param element provides this capability, and it can be nested within a jsp:include element. Listing 2 shows how these elements would be used to pass data into the header.jsp file for a site's main page.

Listing 2. Passing data between JSP pages

<![CDATA[
<%@ page language="java" contentType="text/html" %>
<html>
<head>
     <title>newInstance.com</title>
     <meta http-equiv="Content-Type" 
       content="text/html; charset=iso-8859-1" />
     <link href="/styles/default.css" rel="stylesheet" type="text/css" />
</head>

<body>
<jsp:include page="header.jsp" flush="true">
     <jsp:param name="pageTitle" value="newInstance.com"/>
     <jsp:param name="pageSlogan" 
       value="Java and XML :: Turning theory into practice" />
</jsp:include>
<%@ include file="/navigation.jsp" %>
<jsp:include page="bookshelf.jsp" flush="true" />

<jsp:include page="/mt-blogs/index.jsp" flush="true" />

<%@ include file="/footer.jsp" %>
</body>
</html>
]]>

As you can see, the title is passed in as a slogan.

You've probably noted that you don't actually have to have your JavaBean component available when you set up the page for passing data, because the bean is used only for receiving the data. I always code my bean first, however, and for a very good reason. The JSP parameter names must match the JavaBean property names, and coding the bean first ensures that you set these parameter names properly when coding your JSP page.

Receiving data
With your JSP parameters and JavaBean properties coded, and data being passed into the header.jsp page, the page can begin receiving data. Listing 3 shows the header.jsp page. Most of it is HTML, but be sure to notice the JSP statements, which I'll explain after you've studied the code.

Listing 3. Passing data to other JSP pages

<![CDATA[
<!-- Begin header section -->
<%@ page language="java" contentType="text/html" %>
<jsp:useBean id="pageHeaderInfo"
class="com.newInstance.site.beans.PageHeaderInfo">
     <jsp:setProperty name="pageHeaderInfo" property="*" />
</jsp:useBean>

<table width="100%" border="0" cellspacing="0" cellpadding="0">
     <tr>
       <td width="91" height="50" align="right" valign="top"
           bgcolor="#330066"><font color="#FFFFFF"><img
           src="/images/header-lions.gif" 
           width="90" height="60"></font></td>
       <td colspan="3" align="left" valign="top"
           bgcolor="#000000"><table width="100%" height="60" border="0"
           cellpadding="0" cellspacing="0">
           <tr>
             <td width="261" rowspan="2"><img
               src="/images/header-title.gif" width="261" height="60"></td>
             <td class="pagetitle" width="249" height="55" align="right"
               valign="bottom"><jsp:getProperty name="pageHeaderInfo"
               property="pageSlogan"/></td>
             <td width="10" height="55">&nbsp;</td>
           </tr>
           <tr>
             <td height="5"><img src="/images/spacer.gif" width="1"
               height="5"></td>
             <td height="5"><img src="/images/spacer.gif" width="1"
               height="5"></td>
           </tr>
         </table></td>
       <td width="141" bgcolor="#000000">
         <font color="#FFFFFF">&nbsp;</font>
       </td>
     </tr>
<!-- End header section -->
]]>

The first bit of code identifies the page as a JSP page, and then states that the page needs to access the PageHeaderInfo bean, which is accomplished using the jsp:useBean tag. id sets an alias for the bean that the JSP page can use, and class is the fully qualified Java class name of the bean. Nested within that tag is the jsp:setProperty tag, which specifies that the bean (identified by its alias) should have all available properties set using any request data. This means that for every property in the bean (for example, pageTitle and pageSlogan), a matching request parameter is looked for. These request parameters can come from a client using a Web browser, as well as from other pages that include this JSP page. In this case, the only request data is that created by the parent page. For our example site, the main page (index.jsp) sends pageTitle and pageSlogan, which are set to "newInstance.com" and "Java and XML: Turning theory into practice," respectively.

After the bean's property values have been filled, the page can use that data. In the case of header.jsp, this use occurs further down in the page, and is done using the jsp:getProperty tag. jsp:getProperty takes a name parameter, identifying the object to get data from, and a property parameter, specifying which property of that object should be polled. The value of the property is then inserted into the output of the page, which in turn is inserted into the parent page, resulting in a seamless, dynamic page slogan. And, as simple as that, you're passing data around your JSP pages! You can add as many beans as you want to a JSP page, and each bean can have an unlimited number of properties, accommodating even the most complex request data.

Managing change
Change is every developer's greatest annoyance. It seems inevitable that just when you get your beans coded the way you want them, with all of your properties set and in place and your JSP pages ready to use them, your application or site requirements will change. If the changes call for the addition of a new property (which they often will), you'll have to edit your JavaBean source code, recompile it, and ensure that your JSPs have access to the new bean class. In some cases, however, you may be able to get away with doing nothing. If your pages are storing and receiving properties that are no longer in use (that is, you've ceased to point to a given page component, even though it still exists in the site directory), you may be able to leave the code just as it is. In fact, this happened to me!

The header.jsp page for my personal Web page used to output the head of my HTML site. Once upon a time, this page pulled in a title to use in the title element in the head of my pages. I later changed that, however, and I no longer use the page title in the header JSP page. But I didn't bother to remove the pageTitle property from my PageHeaderInfo bean; in fact, I didn't even remove the jsp:param element from most of the JSP pages that sent the title to the header page. I figured it wasn't worth the effort, and I knew no harm would result from leaving the data there (plus I may need it again one day!). So, if you find yourself in the same situation, don't sweat it -- it's much more fun to spend time adding cool new features than toying with this sort of minutia.

Till next time
Once you're comfortable passing data between your JSP pages, try coding some useful JavaBeans of your own and see if you can get them running on your site. By playing with these beans, along with the jsp:useBean, jsp:param, and jsp:get/setProperty constructs, you should be able to make some cool stuff happen! For the next best practice, I'll show you yet another way to use JSP to bring in external content for your master site. JSTL tags mimic our friendly include tags, and add even more flexibility and capability to JSP. Until then, study up, and I'll see you online.

Resources

About the author
Photo of Brett McLaughlinBrett McLaughlin has been working in computers since the Logo days (remember the little triangle?). He currently specializes in building application infrastructure using Java and Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom Inc. Brett is one of the co-founders of the Java Apache project Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine. Contact Brett at brett@oreilly.com.


69 KBe-mail it!

What do you think of this document?
Killer! (5) Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1)

Comments?



developerWorks > Java technology
developerWorks
  About IBM  |  Privacy  |  Terms of use  |  Contact