Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

7.4 Example: Prime Tag with Variable Length

In this example, we modify the previous prime number example, shown in Section 7.2 (Example: Simple Prime Tag), to provide an attribute for specifying the length of the prime number. Listing 7.8 shows the PrimeTag class, a subclass of SimplePrimeTag that adds support for the length attribute. This change is achieved by supplying an additional method, setLength. When this method is called, it attempts to convert its String argument into an int and store it in an instance variable length. If it fails, the originally initialized value for the instance variable length is used.

The TLD, shown in Listing 7.9, declares the optional attribute length. It is this declaration that tells the container to call the setLength method if the attribute length appears in the tag when it's used in the JSP page.

The JSP page, shown in Listing 7.10, declares the tag library with the taglib directive as before. However, now we are able to specify how long our prime number should be. If we omit the length attribute, the prime tag defaults to 50. Figure 7-2 shows the result of this page.

Listing 7.8. PrimeTag.java

package coreservlets.tags;

/** PrimeTag outputs a random prime number
 *  to the JSP page. The length of the prime number is
 *  specified by the length attribute supplied by the JSP
 *  page. If not supplied, it defaults to 50.
public class PrimeTag extends SimplePrimeTag {
  public void setLength(String length) {
       try {
         this.length = Integer.parseInt(length);
       } catch(NumberFormatException nfe) {
         // Do nothing as length is already set to 50

Listing 7.9. Excerpt from csajsp-taglib.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"

    <description>Outputs an N-digit prime</description>
      <description>N (prime number length)</description>

Listing 7.10. primes-1.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<TITLE>Some N-Digit Primes</TITLE>
<H1>Some N-Digit Primes</H1>
<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
           prefix="csajsp" %>
  <LI>20-digit: <csajsp:prime length="20" />
  <LI>40-digit: <csajsp:prime length="40" />
  <LI>80-digit: <csajsp:prime length="80" />
  <LI>Default (50-digit): <csajsp:prime />
Figure 7-2

Figure 7-2 Result of primes-1.jsp.

  • + Share This
  • 🔖 Save To Your Account