JSP Custom Tags
Outline
Defined
Motivation
Tag Types
Tag Handlers
Tag Library Descriptors
Using Tags in JSPs
Examples
What are Custom Tags?
A custom tag is a user-defined JSP
language element.
JSP custom tags are merely Java
classes that implement special
interfaces.
What are Custom Tags?
When a JSP page containing a custom
tag is translated into a servlet, the tag is
converted to operations on an object
called a tag handler. The Web container
then invokes those operations when the
JSP page's servlet is executed.
Motivation
Better Packaging
By improving the separation between
business logic and presentation.
Encapsulate common functionality
Over a large number of pages and reuse
it. This applies to both HTML
presentation and application logic.
Motivation
Reduce number of Scriptlets
Scriptlets are not reusable.
Eliminate/reduce number of scriptlets in
page.
Simple to use
HTML like syntax, reduces Java code in
the page.
Motivation
P r e s e n ta tio n Im p le m e n ta tio n
HTM L and
H T M L - lik e Ja v a B e a n s
JS P ta g s
C u s to m
JS P T a g s
What can they do?
Produce content for a JSP page
Access a page’s JavaBeans
Introduce new JavaBeans
Introduce new scripting variables
Tag Types
Tags without Body Tags with Body
Syntax In HTML Syntax In HTML
<tagName <tagName
attributeName="value" attributeName="value"
anotherAttributeName anotherAttributeName
="anotherValue"/> ="anotherValue">
...tag body...
</tagName>
Tag Types
Tags without Body Tags with Body
Syntax In JSP Syntax In JSP
<tagLibrary:tagName /> <tagLibrary:tagName>
body
</tagLibrary:tagName>
Tag Handler
A tag handler is an object invoked by the
JSP runtime to evaluate a custom tag
during the execution of a JSP page that
references the tag.
The methods of the tag handler are called
by the implementation class at various
points during the evaluation of the tag.
Every tag handler must implement a
specialized interface.
javax.servlet.jsp.tagext.Tag
All tags must implement Tag interface.
Defines methods the JSP runtime
engine calls to execute a tag.
javax.servlet.jsp.tagext.Tag
public interface Tag {
public final static int SKIP_BODY = 0;
public final static int EVAL_BODY_INCLUDE=1;
public final static int SKIP_PAGE = 5;
public final static int EVAL_PAGE = 6;
void setPageContext(PageContext pageContext);
void setParent(Tag parent);
Tag getParent();
int doStartTag() throws JspException;
int doEndTag() throws JspException;
void release();
}
Interface Tag Fields
static int EVAL_BODY_INCLUDE
Evaluate body into existing out
stream.
static int EVAL_PAGE
Continue evaluating the page.
static int SKIP_BODY
Skip body evaluation.
static int SKIP_PAGE
Skip the rest of the page.
Interface Tag Methods
int doStartTag()
Called by JSP runtime for Tag handler to
process the start tag for this instance.
int doEndTag()
Called by JSP runtime after returning from
doStartTag(). The body of the action may
or may not have been evaluated,
depending on the return value of
doStartTag().
Interface Tag Methods
Tag getParent()
Get the parent (closest enclosing tag
handler) for this tag handler.
void release()
Called on a Tag handler to perform any
cleanup operation.
Interface Tag Methods
void setPageContext(PageContext pc)
Set the current page context. Invoked
before doStartTag() to set the page
context.
void setParent(Tag parent)
Set the parent (closest enclosing tag
handler) of this tag handler. Invoked by
the JSP runtime, prior to doStartTag(), to
pass a tag handler a reference to its
parent tag.
Class TagSupport
A utility base class for defining new tag
handlers implementing Tag interface.
The TagSupport class implements the
Tag and IterationTag interfaces and adds
additional convenience methods
including getter methods for the
properties in Tag
Template for Tag Without Body
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HelloTag extends TagSupport {
public int doStartTag() throws
JspException{
try {
// Java code
} catch (IOException ioe) {
Template for Tag Without Body
throw new JspException("Error: " +
ioe.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
}
Template for Tag With Body
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HelloTag extends TagSupport {
public int doStartTag() throws
JspException{
try {
// Java code
} catch (IOException ioe) {
Template for Tag With Body
throw new JspException("Error: " +
ioe.getMessage());
}
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
}
Tag With Attributes
Also called parameterized tags.
Attributes for customizing behavior of
tag.
Attributes are modeled as JavaBeans
properties.
To add an attribute to tag:
Need a member variable in class to
represent the attribute.
Add a setter method for the attribute.
Tag Life Cycle
O b t a in
h a n d le r
E V A L _ B O D Y _ IN C L U D E
d o S ta r tT a g ( )
S et s e tP a g e C o n te x t( )
p r o p e r t ie s s e tP a r e n t( ) S K IP _ B O D Y P ro c ess b o d y
S e t a t t r ib u t e
v a lu e s
S K IP _ P A G E EVAL_PAG E
d o E n d T ag ()
r e le a s e ( ) r e le a s e ( )
S to p C o n t in u e
Example
A website wants a consistent number
and type of fonts. There are 20
developers all with their own opinion on
what fonts to use. Custom font tag will
need a body, as text will have to go
between its start and end tag. The tag
should have two attributes to alter its
color and size.
MyFontTag.java
package test;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
public class MyFontTag extends TagSupport
{
private String size ="2"; // default size is 2
private String color="#0000FF"; // default color is blue
public void setSize(String str) { this.size = str; }
public void setColor(String str) { this.color = str; }
MyFontTag.java
public int doStartTag() throws JspException {
try
{
pageContext.getOut().print("<font face=\"Arial,
Helvetica, sans-serif\" size=\""+size+"\"
color=\""+color+"\">");
}
catch (Exception e) {
throw new JspException(e.toString());
}
return (EVAL_BODY_INCLUDE);
}
MyFontTag.java
public int doEndTag() throws JspException {
try
{
pageContext.getOut().print("</font>");
}
catch (Exception e) {
throw new JspException(e.toString());
}
return (EVAL_PAGE);
// check with SKIP_PAGE
}
MyFontTag.java
public void release()
{
super.release();
}
}
Note: The font will always be Arial, Helvetica, sans-serif as
this is not an attribute in our tag, but explicitly hard
coded. Its color and size can be altered.
Tag Library Descriptor
Tag syntax is specified by means of Tag
Library Descriptor (TLD)
Specifies mapping between tag names
and classes and how the tag will be
used by JSP runtime that executes tag.
TLD specifies tag attributes
- Attribute names
- Required vs. optional
- Compile-time vs. run-time values
Tag Library Descriptor
The <shortname> tag specifies how the
tag library is going to be referenced from
JSP page.
The <uri> tag can be used as a unique
identifier for tag library.
Tag Library Descriptor
<bodycontent> values can be
i) empty: tag does not has body
ii) tagdependent: any body of the tag
would be handled by the tag itself, and
it can be empty.
iii) JSP: meaning that the JSP
container should evaluate any body of
the tag, but it can also be empty.
Tag Library Descriptor
Tags without bodies must declare that
their body content is empty
If contents of tags are JSP, bodycontent
should be declared as JSP
bodycontent is tagdependent if tag will
interpret the contents of the body as non-
JSP (for instance an SQL statement)
Tag Library Descriptor
Body content containing custom and
core tags, scripting elements, and HTML
text is categorized as JSP; all other types
of body content are tagdependent. Note
that the value of this element does not
affect the interpretation of the body. The
bodycontent element is only intended to
be used by an authoring tool to present
the content of the body.
Tag Library Descriptor
<rtexprvalue> tag is when set to false
specifies that no run time evaluation is
required.
Request-time attribute values must be
JSP expressions:
<css:time timezone=”<%= getTZ()%>”>
Only name and tagclass are mandatory
all other are optional.
Mytaglib.tld
<?xml version="1.0"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.// DTD
JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>ctag</shortname>
<tag>
<name>myfont</name>
<tagclass>test.MyFontTag</tagclass>
<bodycontent>JSP</bodycontent>
Mytaglib.tld
<attribute>
<name>color</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>size</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Referencing Tags
1. Reference the tag library descriptor of an unpacked tag
library using taglib directive
<%@ taglib uri="/WEB-INF/jsp/mytaglib.tld" prefix="first" %>
2. Reference a JAR file containing a tag library
<%@ taglib uri="/WEB-INF/myJARfile.jar" prefix='first" %>
3. Define a reference to the tag library descriptor from the web-
application descriptor (web.xml) and define a short name to
reference the tag library from the JSP.
<taglib><taglib-uri>mytags</taglib-uri>
<taglib-location>/WEB-INF/jsp/ mytaglib.tld</taglib-location>
</taglib>
In JSP
<%@ taglib uri=“mytags" prefix='first" %>
The Custom Tag Library Architecture
CustomTag1.jsp
<HTML>
<HEAD><TITLE>Tag Lib Example</TITLE></HEAD>
<BODY>
<%@ taglib uri="mytaglib.tld" prefix="ctag" %>
To make use of custom tag, in JSP write… <BR>
<ctag:myfont>With default attributes</ctag:myfont>
<BR>Or if you want to change the values from default
<BR>
<ctag:myfont color="#FF0000" size="4">
With given attributes
</ctag:myfont>
</BODY>
</HTML>
Page Compilation
Page
C o m p ile r
t a g l i b d ir e c t iv e ? new TLD? lo a d T L D
c u s to m ta g ? v a lid a t e a t t r ib u t e s y n t a x
T a g E x t r a In f o ? id e n t if y s c r ip t in g v a r ia b le s
a s s o c ia t e v a r ia b le n a m e s a n d c la s s e s
Page Execution
R equest
t a g l i b d ir e c t iv e ? n o a c t io n r e q u ir e d
c u s to m ta g ? n e w ta g ? lo a d t a g h a n d le r
a d d in s t a n c e ( s ) t o r e s o u r c e p o o l
R esponse o b t a in h a n d le r f r o m p o o l
in it ia liz e h a n d le r f o r t a g
e x e c u t e h a n d le r
r e t u r n h a n d le r t o p o o l
Running JSP
1. Create folder “test” in ApacheHome\webapps\examples\jsp.
2. Store file MyFontTag.java in folder “test”.
3. Include servlet.jar in classpath. Location is
ApacheHome\common\lib\servlet.jar
4. Compile MyFontTag.java
5. Store Mytaglib.tld in folder “test”
6. Set classpath ApacheHome\webapps\examples\jsp in a new
window before starting tomcat server.
7. Set classpath ApacheHome\common\lib\servlet.jar in a new
window before starting tomcat server.
8. Start tomcat server
9. Run JSP
http://localhost:7001/examples/jsp/test/CustomTag1.jsp
Result
To make use of custom tag, in JSP write…
With default attributes
Or if you want to change the values from default
With given attributes
Notes
For large project with many developers
and many custom tags in TLD is to
create a jar (e.g MyTagLib.jar) file
containing the custom tag classes and
the TLD (TLD “taglib.tld”, and it should
be placed into /META-INF of jar file)
Once the jar file is in class path custom
tags can be referenced in JSP via
<%@ taglib uri="MyTag.jar" prefix=“ctag"
%>
Notes
In webapps/examples/WEB-INF/web.xml add entry
<taglib>
<taglib-uri>MyTag</taglib-uri>
<taglib-location>/jsp/test/mytaglib.tld
</taglib-location>
</taglib>
In JSP
<%@ taglib uri="MyTag" prefix=“ctag" %>
Tag Library
A tag library is a collection of JSP custom tags.
Tag
Library
JAR
directories
containing
tag handler
packages
MANIFEST.MF
META-INF
taglib.tld
Tags With Body
A tag handler for a tag with a body is
implemented differently depending on
whether the body needs to be evaluated
once or multiple times.
Body Evaluation
Single Evaluation
Multiple Evaluation
E.g. of iteration
Iterate rows, query, search results
Tags With Body
Single Evaluation Multiple Evaluation
Implement interface Tag Implement interface
BodyTag
doStartTag method needs Typically, override
to return doInitBody and
EVAL_BODY_INCLUDE, doAfterBody methods. The
and if it does not need to doInitBody is called after
be evaluated at all then it the body content is set but
should return SKIP_BODY. before it is evaluated, and
the doAfterBody is called
after the body content is
evaluated.
Body Evaluation
A tag handler for a tag with a body is
implemented differently depending on
whether the body needs to be evaluated
once or multiple times.
Body Evaluation
Single Evaluation
Multiple Evaluation
BodyTag Interface
Complex tags implement the BodyTag
interface
- Generate page content
- Conditionally execute body content
- Process content generated by body
- Repeat execution of body content
- Conditionally halt page execution
BodyTagSupport class provides default
implementation
BodyTag Interface
The BodyTag interface extends Tag by
defining additional methods that let a tag
handler access its body. The interface
provides three new methods:
- setBodyContent: Creates body content
and adds to the tag handler
- doInitBody: Called before evaluation of
the tag body
- doAfterBody: Called after evaluation of
the tag body
BodyTag Interface
Tag
implements
Iteration Tag TagSupport
implements
Body Tag BodyTagSupport
BodyTag Life Cycle
O b t a in
h a n d le r
I n it ia liz e s e tB o d y C o n te n t( )
b o d y c o n te n t d o I n it B o d y ( )
S et s e tP a g e C o n te x t( ) d o S ta r tT a g ( )
EVAL_BO D Y_T AG
p r o p e r t ie s s e tP a r e n t()
S K IP _ BO D Y P ro c ess b o d y
S e t a t t r ib u t e
v a lu e s
d o A f te r B o d y ( )
S K IP _ BO D Y EVAL_BO D Y_T AG
S K IP _ P A G E EVAL_PAG E
d o E n d T ag ()
r e le a s e ( ) r e le a s e ( )
S to p C o n t in u e
Single Evaluation
package test;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class ToLowerCaseTag extends BodyTagSupport {
public int doAfterBody() throws JspException {
try {
BodyContent bc = getBodyContent();
String body = bc.getString();
Single Evaluation
JspWriter out = bc.getEnclosingWriter();
if(body != null) {
out.print(body.toLowerCase());
}
} catch(IOException ioe) {
throw new JspException(ioe.getMessage());
}
return SKIP_BODY;
}
}
Single Evaluation
TLD
<tag>
<name>tolowercase</name>
<tagclass>test.ToLowerCaseTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>To lower case tag</info>
</tag>
Single Evaluation
<HTML>
<HEAD><TITLE>To Lower Case Example </TITLE>
</HEAD>
<BODY>
JSP Custom Tag Programming<BR>
<%@ taglib uri="mytaglib.tld" prefix="ctag" %>
<ctag:tolowercase>
JSP Custom Tag Programming
</ctag:tolowercase>
</BODY>
</HTML>
Single Evaluation
Result
JSP Custom Tag Programming
jsp custom tag programming
Single Evaluation
Result
JSP Custom Tag Programming
jsp custom tag programming
Single Evaluation
<HTML>
<HEAD><TITLE>To Lower Case Example </TITLE>
</HEAD>
<BODY>
JSP Custom Tag Programming<BR>
<%@ taglib uri="mytaglib.tld" prefix="ctag" %>
<ctag:tolowercase>
<ctag:myfont color="#FF0000" size="4">
JSP Custom Tag Programming
</ctag:myfont>
</ctag:tolowercase>
</BODY>
</HTML>
Single Evaluation
Result
JSP Custom Tag Programming
jsp custom tag programming
Multiple Evaluation Example
...
taglib uri="mytags" prefix="codecamp"
%>
<OL>
<!-- Repeats N times. A null reps value
means repeat once. -->
<codecamp:repeat reps='<%=
request.getParameter("repeats") %>'>
<LI><codecamp:prime length="40" />
</codecamp:repeat>
</OL>...
Multiple Evaluation
package test;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class IterTag extends BodyTagSupport {
int times = 0;
BodyContent bodyContent;
public void setTimes(int times) { this.times = times; }
public int doStartTag() throws JspException
{
return times >1?EVAL_BODY_AGAIN:SKIP_BODY;
}
Multiple Evaluation
public void setBodyContent(BodyContent bodyContent) {
this.bodyContent = bodyContent;
}
public int doAfterBody() throws JspException {
if (times >1) {
times--;
return EVAL_BODY_AGAIN;
} else
{
return SKIP_BODY;
}
}
Multiple Evaluation
public int doEndTag() throws JspException {
try {
if(bodyContent != null) {
bodyContent.writeOut
(bodyContent.getEnclosingWriter());
}
} catch(IOException e) {
throw new JspException(e.getMessage());
}
return EVAL_PAGE;
}
}
Multiple Evaluation
<tag>
<name>iter</name>
<tagclass>test.IterTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Tag with body and parameter</info>
<attribute>
<name>times</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
Multiple Evaluation
<HTML><HEAD><TITLE>To Lower Case Example</TITLE></HEAD>
<BODY>
JSP Custom Tag Programming<BR>
<%@ taglib uri="mytaglib.tld" prefix="ctag" %>
<ctag:iter times="5">
<ctag:tolowercase>
<ctag:myfont color="#FF0000" size="4">
JSP Custom Tag Programming <BR>
</ctag:myfont>
</ctag:tolowercase>
</ctag:iter>
</BODY>
</HTML>
Multiple Evaluation
Result
JSP Custom Tag Programming
jsp custom tag programming
jsp custom tag programming
jsp custom tag programming
jsp custom tag programming
jsp custom tag programming
Cooperating Tags
<tlt:connection id="con01" ...>
<x:query id="balances">
SELECT account, balance FROM acct_table where
customer_number = <%=request.getCustno()%>
</x:query>
</tlt:connection>
Examples
Ex. For displaying today’s date according to locale.
<%@ taglib uri="/WEB-INF/lib/DateTagLib.tld"
prefix="abc" %>
<HTML>
<HEAD><TITLE>Date tag example</TITLE> </HEAD>
<BODY>
Today is <b><abc:displayDate /></b>
</BODY>
</HTML>
Scripting variables
package test;
import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public final class SecondTag implements Tag {
private PageContext pc = null;
public void setPageContext(PageContext p) {
pc = p;
}
public void setParent(Tag t) {}
public Tag getParent() { return null; }
Scripting variables
public int doStartTag() throws JspException {
Calendar cal = Calendar.getInstance();
pc.setAttribute("time", cal.getTime().toString());
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
public void release() { pc = null; }
}
Scripting variables
package test;
import javax.servlet.jsp.tagext.*;
public class SecondTagTEI extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[] {
new VariableInfo("time", "java.lang.String",
true, VariableInfo.NESTED)
};
}
}
Scripting variables
<tag>
<name>secondtag</name>
<tagclass>test.SecondTag</tagclass>
<teiclass>test.SecondTagTEI</teiclass>
<bodycontent>JSP</bodycontent>
<info>Your second JSP Tag</info>
</tag>
Scripting variables
<html><head<title>SecondTag</title></head>
<body>
<%@ taglib uri="mytaglib.tld" prefix="star"%>
<star:secondtag>
<p>Date value retrieved from JSP Tag:<%=
time %></p>
</star:secondtag>
</body>
</html>
Examples
JSP tags are especially suited for
repetitive tasks such as looping over an
array, doing browser checking, and
validation. Creating hyperlinks is another
such repetitive task.
Multi-destination hyperlinks.
Examples
Examples
<%@ taglib
uri="http://jakarta.apache.org/taglibs/dbta
gs" prefix="sql" %>
<%-- open a db connection --%>
<sql:connection id="conn1">
<sql:url>jdbc:mysql://localhost/test</sql:u
rl>
<sql:driver>org.gjt.mm.mysql.Driver</sql:
driver>
</sql:connection>
Examples
<%-- insert a row into the database --
%>
<sql:statement id="stmt1" conn="conn1">
<%-- set the SQL query --%>
<sql:query>insert into
counters(page,hitCount)
values('<%=request.getRequestURI()%>',
0)
Examples
<%-- the insert may fail, but the page will
continue --%>
<sql:execute ignoreErrors="true"/>
</sql:statement>
Examples
<%-- update the hit counter --%>
<sql:statement id="stmt1" conn="conn1">
<%-- set the SQL query --%>
<sql:query>update counters set hitCount =
hitCount + 1 where page like
'<%=request.getRequestURI()%>'
</sql:query>
<sql:execute/> <%– Execute query --%>
</sql:statement>