Home > Articles > Programming > Java

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

7.10 Example: Prime Tag with Variable Length Using Tag Files

In this section, we rewrite the example of Section 7.4 (Example: Prime Tag with Variable Length) with a JSP-based custom tag. To use attributes with a JSP-based custom tag, each attribute must be declared inside the tag file. This declaration is accomplished by the attribute directive. The attribute directive itself has attributes that provide the same information that the attribute subelements inside the TLD would provide. For example, you can specify whether an attribute is required or not by supplying a required attribute with a value of either true or false. When the value is passed through an attribute to the tag file, it is automatically stored into a scoped variable for access from the JSP EL and into a local variable for access from Java code (scriptlets and scripting expressions). Note once again that because the tag file has the ability to describe itself to the container, no TLD is required.

Listing 7.19 shows prime2.tag declaring an optional attribute called length. Note that we are able to refer to that attribute just like to any other local variable inside the Java code. The JSP page, primes-2.jsp, shown in Listing 7.20, uses our tag file to output prime numbers of different lengths. Figure 7-7 shows the result of primes-2.jsp.

Listing 7.19. prime2.tag

<%@ attribute name="length" required="false" %>
<%
int len = 50;
try {
  len = Integer.parseInt(length);
} catch(NumberFormatException nfe) {}
%>
<%= coreservlets.Primes.nextPrime
      (coreservlets.Primes.random(len)) %>

Listing 7.20. primes-2.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Some N-Digit Primes</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>Some N-Digit Primes</H1>
<%@ taglib tagdir="/WEB-INF/tags" prefix="csajsp" %>
<UL>
  <LI>20-digit: <csajsp:prime2 length="20" />
  <LI>40-digit: <csajsp:prime2 length="40" />
  <LI>80-digit: <csajsp:prime2 length="80" />
  <LI>Default (50-digit): <csajsp:prime2 />
</UL>
</BODY></HTML>
Figure 7-7

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

  • + Share This
  • 🔖 Save To Your Account