0% found this document useful (0 votes)
5 views36 pages

Basic Custom Tags

This document provides an overview of creating custom JSP tag libraries, including the components of a tag library, examples of Java-based and JSP-based tags, and how to define and use them within JSP files. It covers the structure of tag handler classes, tag library descriptor files, and the use of attributes and body content in tags. The document is intended for Java EE training and includes links for further resources and training opportunities.

Uploaded by

letslearn.yes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views36 pages

Basic Custom Tags

This document provides an overview of creating custom JSP tag libraries, including the components of a tag library, examples of Java-based and JSP-based tags, and how to define and use them within JSP files. It covers the structure of tag handler classes, tag library descriptor files, and the use of attributes and body content in tags. The document is intended for Java EE training and includes links for further resources and training opportunities.

Uploaded by

letslearn.yes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

© 2010 Marty Hall

Creating Custom JSP Tag


Libraries: The Basics
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/msajsp.html

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
2 Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2010 Marty Hall

For live Java EE training, please see training courses


at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring, g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP, JSP and this tutorial.tutorial Available at public
venues,Customized
or customized versions
Java EE Training: can be held on-site at your
http://courses.coreservlets.com/
organization. Contact [email protected] for details.
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
• What are tags?
g Whyy use them?
• Java-based tags
– Components of a tag library
– Basic tags
– Tags that use attributes
– Tags that use body content
– Tags that optionally use body content
• JSP
JSP-based
based tags (tag files)
– Components of a tag library
– Basic tags
– Tags that use attributes
– Tags that use body content
4

© 2010 Marty Hall

Intro

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
5 Developed and taught by well-known author and developer. At public venues or onsite at your location.
Uses of JSP Constructs

• Scripting elements calling servlet


Simple code directly
Application
• Scriptingg elements calling
g servlet
code indirectly (by means of utility
classes)
• Beans
B
• Servlet/JSP combo (MVC)
• MVC with
ith JSP expression
i language
l
Complex • Custom tags
Application • MVC with
ith beans,
b custom
t tags,
t andd
a framework like JSF 2.0
6

Tag Examples
Blah, blah, blah. <mytags:showDate/>
Blah blah
Blah, blah, blah
blah. <mytags:showDate format="short"/>
format "short"/>
Blah, blah, blah.

<mytags:emphasize color="red" blink="true" size="100">


This is a very important message
</mytags:emphasize>

Blah, blah, blah.

<mytags:translate language="spanish">
Hello World
</mytags:translate>

7
© 2010 Marty Hall

Java-Based Tags

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
8 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Components That Make Up a


Tag Library
• The Tag Handler Class
– Java code that says what to output
– Must implement javax.servlet.jsp.tagext.SimpleTag
– Usually extends SimpleTagSupport
– Goes in same directories as servlet class files and beans
• The Tag Library Descriptor File
– XML file describing tag name, attributes, and
implementing tag handler class
– Goes under WEB-INF
• The JSP File
– IImports
t a tag
t library
lib (referencing
( f i URL off descriptor
d i t file)
fil )
– Defines tag prefix
9
– Uses tags
Defining a Simple Tag Handler
Class
• Extend the SimpleTagSupport class
• Import needed packages
– import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
javax servlet jsp tagext *;
import java.io.*;
• Override doTag
g
– Obtain the JspWriter with getJspContext().getOut()
– Use the JspWriter to generate output
– Code gets called at request time
• Tag instances are not reused like servlet instances, so no
worryy about race conditions, even if yyou have instance
variables

10

Defining a Simple Tag Handler


Class: Example
package coreservlets.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
p
import j
java.io.*;
import java.math.*;
import coreservlets.Primes;

public class SimplePrimeTag extends SimpleTagSupport {


protected int length = 50;

public
bli void
id d
doTag()
T () th
throws J
JspException,
E ti IOE
IOException
ti {
JspWriter out = getJspContext().getOut();
BigInteger prime =
Primes nextPrime(Primes random(length));
Primes.nextPrime(Primes.random(length));
out.print(prime);
}
11 }
Defining a Simple Tag Library
Descriptor
• Start with XML header
• Top-level element is taglib
– Just use tlib-version and short-name as in example
• Each
E h tag
t defined
d fi d by
b tag element
l t with:
ith
– description, which gives short info. Optional.
– name,
name which defines the base tag name.
name
– tag-class, which gives the fully qualified class name of
the tag handler.
– body-content, which specifies if tag is standalone or
contains content between start and end tag.
• You can have multiple tag entries in each TLD file
• Put TLD file somewhere under WEB-INF
12

TLD File for SimplePrimeTag


<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
// / /
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib ersion>1 0</tlib ersion>
<tlib-version>1.0</tlib-version>
<short-name>csajsp-taglib</short-name>

<tag>
<description>Outputs 50-digit
50 digit primes</description>
<name>simplePrime</name>
<tag-class>coreservlets.tags.SimplePrimeTag</tag-class>
<body-content>empty</body-content>
</tag>
...
</taglib>
• Don’t memorize XML header and standard
part; download and modify online version
– The important thing is to know how to write tag entries
13
– Place TLD file somewhere under WEB-INF
Accessing Custom Tags From
JSP Files
• Import the tag library
– Specify location of TLD file
<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
prefix="csajsp"
prefix csajsp %
%>
– Define a tag prefix (namespace)
<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
prefix="csajsp"
fi " j " %>
• Use the tags
– <prefix:tagName />
• Tag name comes from TLD file
• Prefix comes from taglib directive
– E.g., <csajsp:simplePrime
j i l i /> /

14

Using simplePrime Tag


...
<BODY>
<H1>Some 50-Digit Primes</H1>

<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib


uri= /WEB INF/tlds/csajsp taglib.tld
tld"
prefix="csajsp" %>
<UL>
<LI><csajsp:simplePrime/>
j p p /
<LI><csajsp:simplePrime/>
<LI><csajsp:simplePrime/>
<LI><csajsp:simplePrime/>
j p p
</UL>

</BODY>
</HTML>

15
Using simplePrime Tag:
Result

16

Assigning Attributes to Tags


• Allowing tags like
– <prefix:name
attribute1="value1"
attribute2 value2
attribute2="value2"
...
attributeN="valueN"
/>
• Tags are still standalone
– No body content between start and end tags

17
Attributes:
The Tag Handler Class
• Use of an attribute called attribute1
simply
i l results
l ini a call
ll to a method
h d called
ll d
setAttribute1
– Attribute value is supplied to method as a String
• Example
– To support

<prefix:tagName attribute1="Test" />

add the following to tag handler class:

public
bli void
id setAttribute1(String
ib ( i value1)
l ){
doSomethingWith(value1);
18 }

Attributes: PrimeTag.java
package coreservlets.tags;

public class PrimeTag extends SimplePrimeTag {


public void setLength(String
p g g length)
g {
try {
this.length = Integer.parseInt(length);
} catch(NumberFormatException nfe) {
this.length = 50;
}
}
}

19
Attributes:
The Tag Library Descriptor File
• The tag element must contain a nested
attribute element
l t
• The attribute element has three further-
nested elements
– name, a required element that defines the case-sensitive
attribute name.
– required, a required element that stipulates whether the
attribute must always be supplied (true) or is optional
(false).
(false)
– rtexprvalue, an optional attribute that indicates whether
p
the attribute value can be a JSP expression like
<%= expression %> (true) or whether it must be a fixed
string (false). The default value is false.
20

TLD File for PrimeTag


...
<taglib ...>>
...
<tag>
<description>Outputs an N-digit
N digit prime</description>
<name>prime</name>
<tag-class>coreservlets.tags.PrimeTag</tag-class>
<body content>empty</body content>
<body-content>empty</body-content>
<attribute>
<name>length</name>
<required>false</required>
equ ed a se / equ ed
</attribute>
</tag>
...
</taglib>

21
Using prime Tag
...
<BODY>
<H1>Some N-Digit Primes</H1>

<%@ taglib
g uri="/WEB-INF/tlds/csajsp-taglib.tld"
j p g
prefix="csajsp" %>
<UL>
<LI>20-digit: <csajsp:prime length="20"/>
<LI>40-digit:
40 di i <csajsp:prime
j i l
length="40"/>
h 40 /
<LI>80-digit: <csajsp:prime length="80"/>
<LI>Default (50-digit): <csajsp:prime/>
</UL>

</BODY>
</HTML>

22

Using prime Tag: Result

23
Including the Tag Body
• Simplest tags
– <prefix:tagName/>
• Tags with attributes
– <prefix:tagName
fi N att1="val1"
1 " l1" ... //>
• Now
– <prefix:tagName>
Scriptless JSP Content
</prefix:tagName>

– <prefix:tagName att1="val1" ... >


Scriptless JSP Content
</prefix:tagName>
24

Including Tag Body:


The Tag Handler Class
• Call getJspBody().invoke(null);
g p y() ( )
public void doTag() throws ... {
JspWriter out = getJspContext().getOut();
out.print("...");
getJspBody().invoke(null);
p ( );
out.print("...");
}

25
Including Tag Body:
HeadingTag java
HeadingTag.java
public class HeadingTag extends SimpleTagSupport {
private String
p g align;
g
private String bgColor;
private String border;
private String fgColor;
private String font;
private String size;

public void setAlign(String align) {


this align = align;
this.align
}

public void setBgColor(String bgColor) {


thi b C l
this.bgColor = b
bgColor;
C l
}

public void setBorder(String border) {


this.border = border;
}…
26

Including Tag Body:


HeadingTag java (Continued)
HeadingTag.java
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.print("<TABLE ALIGN=\"" + align + "\"\n" +
" BGCOLOR=\"" + bgColor + "\"\n" +
" BORDER=" + border + "\">\n");
out.print("<TR><TH>");
out.print("<SPAN STYLE=\"color: " + fgColor + ";\n" +
" font-family: " + font + ";\n"
;\n +
" font-size: " + size + "px; " +
"\">\n");
// Output content of the body
getJspBody().invoke(null);
out.println("</SPAN></TH></TR></TABLE>" +
"<BR CLEAR=\"ALL\"><BR>");
}
}

27
Using Tag Body:
The Tag Library Descriptor File
• Only difference is body-content element
– Should
Sh ld bbe scriptless
i tl i
instead
d off empty:
t
<tag>
<name>…</name>
<tag-class>
<tag class>…</tag
</tag-class>
class>
<body-content>scriptless</body-content>
</tag>
• Legal values for body-content
– empty: no body content
• Body content is ignored even if supplied
– scriptless: body content is included
• Can contain plain text, EL elements, other custom tags,
and p
page
g directives
• No explicit scripting allowed (<%= ... %>)
– tagdependent: body content is processed by tag
28

heading Tag: TLD File


<tag>
<description>Formats enclosed heading</description>
<name>heading</name>
<tag-class>coreservlets.tags.HeadingTag</tag-class>
<body content>scriptless</body content>
<body-content>scriptless</body-content>
<attribute>
<name>align</name>
<required>true</required>
</attribute>
<attribute>
<name>bgColor</name>
a e bgCo o / a e
<required>true</required>
</attribute>
...
</tag>

29
Using heading Tag

<BODY>
<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
prefix="csajsp" %>
<csajsp:heading align="LEFT" bgColor="CYAN"
border="10" fgColor="BLACK"
font="Arial Black" size="78">
First Heading
</csajsp:heading>
<csajsp:heading align="RIGHT" bgColor="RED"
border="1" fgColor="YELLOW"
font="Times New Roman" size="50">
Second Heading
</csajsp:heading>
<csajsp:heading align="CENTER" bgColor="#C0C0C0"
border="20" fgColor="BLUE"
font="Arial Narrow" size="100">
Third Heading
</csajsp:heading>
30

Using heading Tag:


Results

31
Optional Tag Bodies
• First examples
– No tag bodies
• body-content: empty
• doTag does not call invoke(null)
• Most recent examples
– Always included tag bodies
• body-content: scriptless
• doTag calls invoke(null)
• Now:
– Decide at request time whether or not to include tag body
• body-content: scriptless
• doTag conditionally calls invoke(null)
– Depending on run-time information
32

Optional Tag Bodies:


DebugTag java
DebugTag.java
public class DebugTag
p g g extends SimpleTagSupport
p g pp {
public void doTag() throws JspException, IOException {
PageContext context = (PageContext)getJspContext();
HttpServletRequest request =
(HttpServletRequest)context.getRequest();
// Output body of tag only if debug param is present.
if (request.getParameter("debug") != null) {
getJspBody().invoke(null);
}
}
}

33
TLD File for DebugTag
...
<tag>
<description>
Conditionally outputs enclosed body
</description>
<name>debug</name>
<tag-class>coreservlets.tags.DebugTag</tag-class>
<b d
<body-content>scriptless</body-content>
t t> i tl </b d t t>
</tag>
...

34

Using debug Tag


<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
prefix="csajsp"
prefix= csajsp %>
Top of regular page. Blah, blah, blah.
Yadda, yadda, yadda.
<csajsp:debug>
<H2>Debug Info:</H2>
********************<BR>
-Remote
R t HHost:
t ${${pageContext.request.remoteHost}<BR>
C t t t t H t}<BR>
-Session ID: ${pageContext.session.id}<BR>
-The foo parameter: ${param.foo}<BR>
********************<BR>
</csajsp:debug>
<P>
Bottom of regular page. Blah, blah, blah.
Yadda, yadda, yadda.
35
Using debug Tag: Results

36

© 2010 Marty Hall

Using a Pseudo-URI
Instead of TLD Location

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
37 Developed and taught by well-known author and developer. At public venues or onsite at your location.
The <uri> Tag in TLD Files
• TLD files can define fake addresses
<?xml
? l version="1.0"
i "1 0" encoding="UTF-8"
di " 8" ??>
<taglib ...> ...
<uri>http://anything/you/want</uri>
• JSP pages import TLD using fake address
<%@ taglib uri="http://anything/you/want" ...%>
• Note: this address is totally made up: it just matches what is in the TLD file.
JSP page does not connect to the Web to look for this address.
• Advantages
– Can move/rename TLD file with no JSP code changes
• You can even bundle tag libraries in JAR files under WEB
WEB-INF/lib
INF/lib and put
TLD files in META-INF in the JAR files
– If you write JSP pages using XML syntax, you can use an additional xmlns
entry to the root element and omit the @taglib declaration.
• Disadvantage
– Confusing: JSP authors don’t know where TLD file is
38

Example:
p The <uri> Tag
g
• TLD File • JSP (Approach 1)
– In
I WEB
WEB-INF/tlds/file.tld
INF/ ld /fil ld <%@ t
taglib
lib
uri="/WEB-INF/tlds/file.tld"
<?xml ... ?> prefix="myPrefix" %>
<taglib ...> ...
<uri> <myPrefix:myTag/>
http://foo.com/bar ...
</uri>
• JSP (A
(Approach
h 2)
<tag> <%@ taglib
<name>myTag</name> uri="http://foo.com/bar"
<tag-class>...</tag-class>
g g prefix="myPrefix"
prefix myPrefix %>
<body-content> ...
empty or scriptless <myPrefix:myTag/>
</body-content> ...
</tag>
</taglib>

39
© 2010 Marty Hall

JSP-Based Tags
((Tag
g Files))

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
40 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Tag Files:
Custom Tags Using JSP Syntax
• Two Approaches
– When there is lots of logic, use Java to create output
• Analagous to when you use servlets
– When there is lots of formatting,
formatting use JSP to create output
• Analagous to when you use JSP pages
• Pros
– Very good for complex text formatting
– Very concise
• Cons
C
– Not good for complicated logic
– Runs only in JSP 22.0
0 and later
• Java-based versions had “classic” syntax that worked in
older servers (e.g., BEA WebLogic 8.1, Oracle 9i AS)
41
Simple Standalone Tags
• Java-based approach requires three pieces
– Java code that overrides doTag to generate output
• Strengths and weaknesses generally similar to those of
servlets,, but more cumbersome
– Tag Library Descriptor (TLD) file that maps Java class
name to tag name
– JSP page th
thatt refers
f tto specific
ifi llocation
ti off TLD file
fil
• JSP-based approach requires two pieces
– JSP code (tag file) that shows result
• /WEB-INF/tags/someName.tag
– No TLD file: tag name taken from tag-file name
– JSP page that refers to directory containing tag file
• /WEB-INF/tags or a subdirectory thereof
42

Tag
g Files
• Look just like regular JSP files, except
– Must bbe llocated
M d iin (or
( under)
d ) WEB-INF/tags
WEB INF/
– Must be named blah.tag, not blah.jsp
– You use <%@ tag ... %> instead of <%@ page ... %>
– You use predefined variable jspContext instead of pageContext
• But you can cast it to PageContext
• Other variables (request, response, etc.) are the same
• Example
WEB-INF/tags/date.tag some-page.jsp

<%@ tag import="java.util.*" %> <%@ taglib


Date is <%= new Date() %> tagdir="/WEB-INF/tags"
prefix="test"
prefix= test %>
...
<test:date/>
43
Java-Based Tags: Code
(Simple Standalone Tag)
package coreservlets.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
p
import j
java.io.*;
import java.math.*;
import coreservlets.Primes;

public class SimplePrimeTag extends SimpleTagSupport {


protected int length = 50;

public
bli void
id doTag()
d T () th
throws J
JspException,
E ti IOE
IOException
ti {
JspWriter out = getJspContext().getOut();
BigInteger prime =
Primes nextPrime(Primes random(length));
Primes.nextPrime(Primes.random(length));
out.print(prime);
}
44 }

Java-Based Tags: TLD File


(Simple Standalone Tag)
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns http://java.sun.com/xml/ns/j2ee
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>csajsp-taglib</short-name>

<tag>
<description>Outputs 50-digit primes</description>
<name>simplePrime</name>
<tag-class>coreservlets.tags.SimplePrimeTag</tag-class>
<body-content>empty</body-content>
</tag>
...
</taglib>

45
Java-Based Tags: Usage in JSP
(Simple Standalone Tag)
...
<BODY>
<H1>Some 50-Digit Primes</H1>
<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
prefix="csajsp" %>
<UL>
<LI><csajsp:simplePrime/>
<LI><csajsp:simplePrime/>
<LI><csajsp:simplePrime/>
<LI><
<LI><csajsp:simplePrime/>
j i l P i />
</UL>
</BODY></HTML>

46

Java-Based Tags: Result


(Simple Standalone Tag)

47
Tag Files: Tag Code
(Simple Standalone Tag)
• WEB-INF/tags/simplePrime2.tag
– Directory name is not arbitrary; must be in
/WEB-INF/tags or a subdirectory thereof

<%= coreservlets.Primes.nextPrime
(coreservlets.Primes.random(50)) %>

48

Tag Files: Usage in JSP


(Simple Standalone Tag)
...
<BODY>
<H1>Some 50-Digit Primes</H1>

<%@ taglib tagdir="/WEB-INF/tags"


tagdir /WEB INF/tags
prefix="csajsp" %>
<UL>
<LI><csajsp:simplePrime2/>
j p p /
<LI><csajsp:simplePrime2/>
<LI><csajsp:simplePrime2/>
<LI><csajsp:simplePrime2/>
j p p
</UL>
</BODY></HTML>

49
Tag Files: Result
(Simple Standalone Tag)

50

Tags with Attributes


• Java-based tags
– For each attribute, add setAttributeName method to the
Java class
– Attribute value usually explicitly stored in instance
variable (field) of Java class
– List each attribute explicitly in TLD file
• JSP-based tags (tag files)
– Each attribute listed in tag file with @attribute
• Can
C also
l lilistt required
i d and
d rtexprvalue
t l (d(default
f lt ffalse)
l )
– Attribute value automatically stored in scoped variable
((for access from expression
p language)
g g ) and in local
variable (for access from Java code)
– No TLD file
51
Java-Based Tags: Code
(Tag with Attributes)
package coreservlets.tags;

public class PrimeTag extends SimplePrimeTag {


public void setLength(String length) {
try {
this.length = Integer.parseInt(length);
} catch(NumberFormatException nfe) {
thi l
this.length
th = 50
50;
}
}
}

52

Java-Based Tags: TLD File


(Tag with Attributes)

<tag>
<description>Outputs an N-digit prime</description>
<name>prime</name>
<tag-class>coreservlets
<tag class>coreservlets.tags.PrimeTag</tag
tags PrimeTag</tag-class>
class>
<body-content>empty</body-content>
<attribute>
<name>length</name>
<required>false</required>
</attribute>
</tag>
/tag

53
Java-Based Tags: Usage in JSP
(Tag with Attributes)

<BODY>
<H1>Some N-Digit Primes</H1>
<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"
prefix="csajsp" %>
<UL>
<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):
g ) <csajsp:prime
j p p /
/>
</UL>
</BODY></HTML>

54

Java-Based Tags: Results


(Tag with Attributes)

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

56

Tag Files: Usage in JSP


(Tag with Attributes)

<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):
g ) <csajsp:prime2/>
j p p /
</UL>
</BODY></HTML>

57
Tag Files: Results
(Tag with Attributes)

58

Tags with Bodies


• Java-based tags
– Change body-content from empty to scriptless (in TLD)
– Call getJspBody().invoke(null)
– Still need setter method and TLD entry for every attribute

• JSP
JSP-based
based tags (tag files)
– Use <jsp:doBody/> to output tag body
– No major syntax changes
– Access to attributes still much simpler

59
Java-Based Tags: Code
(Tag with Body)
public class HeadingTag extends SimpleTagSupport {
private String
p g align;
g
private String bgColor;
private String border;
private String fgColor;
private String font;
private String size;

public void setAlign(String align) {


this align = align;
this.align
}

public void setBgColor(String bgColor) {


thi b C l
this.bgColor = b
bgColor;
C l
}

public void setBorder(String border) {


this.border = border;
}…
60

Java-Based Tags: Code


(Tag with Body -- Continued)
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.print("<TABLE ALIGN=\"" + align + "\"\n" +
" BGCOLOR=\"" + bgColor + "\"\n" +
" BORDER=" + border + "\">\n");
out.print("<TR><TH>");
out.print("<SPAN STYLE=\"color: " + fgColor + ";\n" +
" font-family: " + font + ";\n"
;\n +
" font-size: " + size + "px; " +
"\">\n"); //
// Output content of the body
getJspBody().invoke(null);
out.println("</SPAN></TH></TR></TABLE>" +
"<BR CLEAR=\"ALL\"><BR>");
}
}

61
Java-Based Tags: TLD File
(Tag with Body)
...
<tag>
g
<description>Formats enclosed heading</description>
<name>heading</name>
<tag-class>coreservlets.tags.HeadingTag</tag-class>
<body content>scriptless</body content>
<body-content>scriptless</body-content>
<attribute>
<name>align</name>
<required>true</required>
</attribute>
<attribute>
<name>bgColor</name>
<required>true</required>
</attribute>
...
</tag>

62

Java-Based Tags: Usage in JSP


(Tag with Body)
<BODY>
<%@ taglib
g uri="/WEB-INF/tlds/csajsp-taglib.tld"
/ / / j p g
prefix="csajsp" %>
<csajsp:heading align="LEFT" bgColor="CYAN"
border="10" fgColor="BLACK"
font="Arial Black" size="78">
First Heading
</csajsp:heading>
<csajsp:heading align="RIGHT" bgColor="RED"
border="1" fgColor="YELLOW"
font="Times New Roman" size="50">
Second Heading
</csajsp:heading>
<csajsp:heading align="CENTER" bgColor="#C0C0C0"
border="20" fgColor="BLUE"
font="Arial Narrow" size="100">
Third Heading
</csajsp:heading>
63
Java-Based Tags: Results
(Tag with Body)

64

Tag Files: Tag Code


(Tag with Body)
<%@ attribute name="align" required="true" %>
<%@ attribute name="bgColor"
name= bgColor required=
required="true"
true %>
<%@ attribute name="border" required="true" %>
<%@ attribute name="fgColor" required="true" %>
<%@ attribute name="font" required="true" %>
<%@ attribute name="size" required="true" %>
<TABLE ALIGN="${align}"
BGCOLOR "${b C l }"
BGCOLOR="${bgColor}"
BORDER="${border}">
<TR><TH>
<SPAN STYLE="color: ${fgColor};
$
font-family: ${font};
font-size: ${size}px;">
<jsp:doBody/></SPAN>
</TABLE><BR CLEAR="ALL"><BR>
65
Tag Files: Usage in JSP
(Tag with Body)
<BODY>
<%@ taglib
g tagdir="/WEB-INF/tags"
g / / g
prefix="csajsp" %>
<csajsp:heading2 align="LEFT" bgColor="CYAN"
border="10" fgColor="BLACK"
font="Arial Black" size="78">
First Heading
</csajsp:heading2>
<csajsp:heading2 align="RIGHT" bgColor="RED"
border="1" fgColor="YELLOW"
font="Times New Roman" size="50">
Second Heading
</csajsp:heading2>
<csajsp:heading2 align="CENTER" bgColor="#C0C0C0"
border="20" fgColor="BLUE"
font="Arial Narrow" size="100">
Third Heading
</csajsp:heading2>
66

Tag Files: Results


(Tag with Body)

67
© 2010 Marty Hall

Wrap-Up

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
68 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Open Source Tag Libraries


• JSP Standard Tag Library (JSTL)
– Covered
C d in
i later
l t lecture
l t
• AjaxTags
– Simple
p Ajax
j functionalityy without writingg JavaScript
p
• http://ajaxtags.sourceforge.net/
• DisplayTag
– Super
Super-fancy
fancy table creator
• http://displaytag.sourceforge.net/1.2/
• Listing of other open-source tag libraries
– http://java-source.net/open-source/jsp-tag-libraries
http://ja a so rce net/open so rce/jsp tag libraries
• Google queries and searching
• Google maps wrappers
• Menus
• Paging of large data sets
• Fancy UIs
69
Summary: Java-Based Tags
• Tag handler class
– Extend
E t d SimpleTagSupport
Si l T S t
– Override doTag
– Get the JspWriter with getJspContext().getOut()
– U the
Use h JspWriter
J W i to generate output
– Output tag body with getJspBody().invoke(null);
– Define setBlah for each attribute named blah
• TLD File (/WEB-INF/.../somefile.tld)
– <tag> ... </tag>
• Contains description (optional), name, tag-class,
b d
body-content,
t t attribute
tt ib t (one
( for
f each h attribute)
tt ib t )
– <uri>http://fake-address</uri> (optional)
• JSP File
– <%@ taglib uri="/WEB-INF/.../somefile.tld" prefix="blah" %>
• Or <%@ taglib uri="http://fake-address" prefix="blah" %>
70
– <blah:tagName/> or <blah:tagName>...</blah:tagName>

Summary: Tag Files


• Tag File
– /WEB-INF/tags/tagName.tag
– Create chunk of JSP that generates the output
– Declare
l attributes
ib with
i h <%@
%@ attribute
ib ...%>
%
– Output attributes with ${attributeName}
– Output the tag body with <jsp:doBody/>
– Refactor Java code so methods take strings as args
• JSP File
– <%@ taglib tagdir="/WEB-INF/tags prefix="blah" %>
– <blah:tagName/>
g or
<blah:tagName>...</blah:tagName>
71
© 2010 Marty Hall

Questions?

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
72 Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like