CS396N - Web Programming
Spring 2002
Chapter 20 - Java Server Pages - JSP

Using JavaBeans Components with JSP

Example - StringBean.java

package cwp;

/** A simple bean that has a single String property
 *  called message.
 *
 */

public class StringBean {
  private String message = "No message specified";

  public String getMessage() {
    return(message);
  }

  public void setMessage(String message) {
    this.message = message;
  }
}
 

Example - StringBean.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Simple example of jsp:useBean and manipulating properties
with jsp:setProperty and jsp:getProperty and
with explicit Java code in scriptlets and expressions.
-->
<HTML>
<HEAD>
<TITLE>Using JavaBeans with JSP</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Using JavaBeans with JSP</TABLE>
<jsp:useBean id="stringBean" class="cwp.StringBean" />
<OL>
<LI>Initial value (getProperty):
    <I><jsp:getProperty name="stringBean"
                        property="message" /></I>
<LI>Initial value (JSP expression):
    <I><%= stringBean.getMessage() %></I>
<LI><jsp:setProperty name="stringBean"
                     property="message"
                     value="Best string bean: Fortex" />
    Value after setting property with setProperty:
    <I><jsp:getProperty name="stringBean"
                        property="message" /></I>
<LI><% stringBean.setMessage("My favorite: Kentucky Wonder"); %>
    Value after setting property with scriptlet:
    <I><%= stringBean.getMessage() %></I>
</OL>
</BODY>
</HTML>

Result


 

Example - SaleEntry1.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Example of using jsp:setProperty with an explicit value
supplied to the "value" attribute. See SaleEntry2.jsp
and SaleEntry3.jsp for alternatives.
-->
<HTML>
<HEAD>
<TITLE>Using jsp:setProperty</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Using jsp:setProperty</TABLE>
<jsp:useBean id="entry" class="cwp.SaleEntry" />
<jsp:setProperty
    name="entry"
    property="itemID"
    value='<%= request.getParameter("itemID") %>' />
<%
int numItemsOrdered = 1;
try {
  numItemsOrdered =
    Integer.parseInt(request.getParameter("numItems"));
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty
    name="entry"
    property="numItems"
    value="<%= numItemsOrdered %>" />
<%
double discountCode = 1.0;
try {
  String discountString =
    request.getParameter("discountCode");
  // Double.parseDouble not available in JDK 1.1.
  discountCode =
    Double.valueOf(discountString).doubleValue();
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty
    name="entry"
    property="discountCode"
    value="<%= discountCode %>" />
<BR>
<TABLE ALIGN="CENTER" BORDER=1>
<TR CLASS="COLORED">
  <TH>Item ID<TH>Unit Price<TH>Number Ordered<TH>Total Price
<TR ALIGN="RIGHT">
  <TD><jsp:getProperty name="entry" property="itemID" />
  <TD>$<jsp:getProperty name="entry" property="itemCost" />
  <TD><jsp:getProperty name="entry" property="numItems" />
  <TD>$<jsp:getProperty name="entry" property="totalCost" />
</TABLE>
</BODY>
</HTML>

Example - SaleEntry.java

package cwp;

/** Simple bean to illustrate the various forms
 *  of jsp:setProperty.
 */

public class SaleEntry {
  private String itemID = "unknown";
  private double discountCode = 1.0;
  private int numItems = 0;

  public String getItemID() {
    return(itemID);
  }

  public void setItemID(String itemID) {
    if (itemID != null) {
      this.itemID = itemID;
    } else {
      this.itemID = "unknown";
    }
  }

  public double getDiscountCode() {
    return(discountCode);
  }

  public void setDiscountCode(double discountCode) {
    this.discountCode = discountCode;
  }

  public int getNumItems() {
    return(numItems);
  }

  public void setNumItems(int numItems) {
    this.numItems = numItems;
  }

  // In real life, replace this with database lookup.

  public double getItemCost() {
    double cost;
    if (itemID.equals("a1234")) {
      cost = 12.99*getDiscountCode();
    } else {
      cost = -9999;
    }
    return(roundToPennies(cost));
  }

  private double roundToPennies(double cost) {
    return(Math.floor(cost*100)/100.0);
  }

  public double getTotalCost() {
    return(getItemCost() * getNumItems());
  }
}
 
 


 


 
 


Example - SharedCounts1.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Example of sharing beans.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
http://www.corewebprogramming.com/.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Shared Access Counts: Page 1</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>

<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Shared Access Counts: Page 1</TABLE>
<P>
<jsp:useBean id="counter"
             class="cwp.AccessCountBean"
            scope="application">
  <jsp:setProperty name="counter"
                   property="firstPage"
                   value="SharedCounts1.jsp" />
</jsp:useBean>

Of SharedCounts1.jsp (this page),
<A HREF="SharedCounts2.jsp">SharedCounts2.jsp</A>, and
<A HREF="SharedCounts3.jsp">SharedCounts3.jsp</A>,
<jsp:getProperty name="counter" property="firstPage" />
was the first page accessed.
<P>
Collectively, the three pages have been accessed
<jsp:getProperty name="counter" property="accessCount" />
times.

</BODY>
</HTML>

Example - AccessCountBean.java
package cwp;

/** Simple bean to illustrate sharing beans through
 *  use of the scope attribute of jsp:useBean.
 */

public class AccessCountBean {
  private String firstPage;
  private int accessCount = 1;

  public String getFirstPage() {
    return(firstPage);
  }

  public void setFirstPage(String firstPage) {
    this.firstPage = firstPage;
  }

  public int getAccessCount() {
    return(accessCount++);
  }
}
 

Output


 

Creating Custom JSP Tag Libraries


 

Example - ExampleTag.java - a simple tag handler
package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Very simple JSP tag that just inserts a string
 *  ("Custom tag example...") into the output.
 *  The actual name of the tag is not defined here;
 *  that is given by the Tag Library Descriptor (TLD)
 *  file that is referenced by the taglib directive
 *  in the JSP file.
 */

public class ExampleTag extends TagSupport {
  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("Custom tag example " +
                "(cwp.tags.ExampleTag)");
    } catch(IOException ioe) {
      System.out.println("Error in ExampleTag: " + ioe);
    }
    return(SKIP_BODY);
  }
}
 

Example - cwp-taglib.tld - tag library descriptor file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
 PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
 "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<!-- a tag library descriptor -->

<taglib>
  <!-- after this the default space is
        "http://java.sun.com/j2ee/dtds/jsptaglibrary_1_2.dtd"
   -->

  <tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>cwp</shortname>
  <!-- ** CHANGED FROM "urn" TO "uri" IN TOMCAT 3.1 final ** -->
  <uri></uri>
  <info>
    A tag library from Core Web Programming Java 2 Edition,
    http://www.corewebprogramming.com/.
  </info>

<!--
  <tag>
    The name (after prefix) tag will have in JSP code
    <name>example</name>

    The actual class implementing tag. In
    Tomcat 3.1, it MUST be in a package.
    <tagclass>cwp.tags.ExampleTag</tagclass>

    Descriptive information about tag.
    <info>Simplest example: inserts one line of output</info>

    One of three values describing what goes between
    start and end tag.
      empty: no body
      JSP: body that is evaluated by container normally,
           then possibly processed by tag
      tagdependent: body is only processed by tag;
                    JSP in body is not evaluated.
    ** NOTE: TOMCAT 3.1 FINAL DOES NOT SUPPORT BODYCONTENT **
    ** THE BETA SUPPORTED IT, AND IT IS PART OF SPEC, BUT... **
    <bodycontent>empty</bodycontent>
  </tag>
-->

  <tag>
    <name>example</name>
    <tagclass>cwp.tags.ExampleTag</tagclass>
    <info>Simplest example: inserts one line of output</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>empty</bodycontent> -->
  </tag>

  <tag>
    <name>simplePrime</name>
    <tagclass>cwp.tags.SimplePrimeTag</tagclass>
    <info>Outputs a random 50-digit prime.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>empty</bodycontent> -->
  </tag>

  <tag>
    <name>prime</name>
    <tagclass>cwp.tags.PrimeTag</tagclass>
    <info>Outputs a random N-digit prime.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>empty</bodycontent> -->
    <attribute>
      <name>length</name>
      <required>false</required>
    </attribute>
  </tag>

  <tag>
    <name>heading</name>
    <tagclass>cwp.tags.HeadingTag</tagclass>
    <info>Outputs a 1-cell table used as a heading.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
    <attribute>
      <name>bgColor</name>
      <required>true</required>  <!-- bgColor is required -->
    </attribute>
    <attribute>
      <name>color</name>
      <required>false</required>
    </attribute>
    <attribute>
      <name>align</name>
      <required>false</required>
    </attribute>
    <attribute>
      <name>fontSize</name>
      <required>false</required>
    </attribute>
    <attribute>
      <name>fontList</name>
      <required>false</required>
    </attribute>
    <attribute>
      <name>border</name>
      <required>false</required>
    </attribute>
    <attribute>
      <name>width</name>
      <required>false</required>
    </attribute>
  </tag>

  <tag>
    <name>debug</name>
    <tagclass>cwp.tags.DebugTag</tagclass>
    <info>Includes body only if debug param is set.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
  </tag>

  <tag>
    <name>filter</name>
    <tagclass>cwp.tags.FilterTag</tagclass>
    <info>Replaces HTML-specific characters in body.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
  </tag>

  <tag>
    <name>repeat</name>
    <tagclass>cwp.tags.RepeatTag</tagclass>
    <info>Repeats body the specified number of times.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
    <attribute>
      <name>reps</name>
      <required>true</required>
      <!-- rtexprvalue indicates whether attribute
           can be a JSP expression. -->
      <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>

  <tag>
    <name>if</name>
    <tagclass>cwp.tags.IfTag</tagclass>
    <info>if/condition/then/else tag.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
  </tag>

  <tag>
    <name>condition</name>
    <tagclass>cwp.tags.IfConditionTag</tagclass>
    <info>condition part of if/condition/then/else tag.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
  </tag>

  <tag>
    <name>then</name>
    <tagclass>cwp.tags.IfThenTag</tagclass>
    <info>then part of if/condition/then/else tag.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
  </tag>

  <tag>
    <name>else</name>
    <tagclass>cwp.tags.IfElseTag</tagclass>
    <info>else part of if/condition/then/else tag.</info>
    <!-- TOMCAT 3.1 DOES NOT SUPPORT BODYCONTENT
    <bodycontent>JSP</bodycontent> -->
  </tag>

</taglib>
 

Example - SimplePrimeTag.java
package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.math.*;
import cwp.*;

/** Generates a prime of approximately 50 digits.
 *  (50 is actually the length of the random number
 *  generated -- the first prime above that number will
 *  be returned.)
 */

public class SimplePrimeTag extends TagSupport {
  protected int len = 50;
 
  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      BigInteger prime = Primes.nextPrime(Primes.random(len));
      out.print(prime);
    } catch(IOException ioe) {
      System.out.println("Error generating prime: " + ioe);
    }
    return(SKIP_BODY);
  }
}

Example - SimplePrimeExample.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of SimplePrimeTag tag.

-->
<HTML>
<HEAD>
<TITLE>Some 50-Digit Primes</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>Some 50-Digit Primes</H1>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<UL>
  <LI><cwp:simplePrime />
  <LI><cwp:simplePrime />
  <LI><cwp:simplePrime />
  <LI><cwp:simplePrime />
</UL>
</BODY>
</HTML>
 


 
 


 

Integrating Servlets with JSP