JSP 1.2 Custom Tags
JSP 1.2 Custom Tags
2
Custom Tags
1
Disclaimer & Acknowledgments
● Even though Sang Shin is a full-time employees of Sun
Microsystems, the contents here are created as his own personal
endeavor and thus does not reflect any official stance of Sun
Microsystems.
● Sun Microsystems is not responsible for any inaccuracies in the
contents.
● Acknowledgements
– The slides, speaker notes, and example code of this
presentation are created from
● “Core Servlets and JavaServer Pages” book written by
Marty Hall
● “Custom Tags” section of Java WSDP 1.2 tutorial written by
3
Agenda I
● Evolution of Web-tier technology
● What is and why custom tags?
● Components that make up custom tag
architecture
● How to build, configure, and deploy
custom tag library?
● How does it work?
4
Agenda II
● Usage scenarios of custom tags (in the
increasing order of complexity)
– Defining a tag without attributes or tag bodies
– Assigning attributes to tags
– Including tag body
– Optionally including tag body
– Manipulating tag body
– Including or manipulating tag body multiple
times
– Using nested tags
5
Evolution of
Web tier technology
6
Web Application Designs
7
Where does custom tags fit in?
8
Standard Action Tags (or Tags)
● <jsp:useBean>
– Instantiate JavaBean object
● <jsp:getProperty>
– Allow accessing bean properties
● <jsp:setProperty>
– Allow setting bean properties
9
Standard Action Tags (or Tags)
● <jsp:forward>
– Forwards request to another HTML page, JSP, or
servlet
● <jsp:include>
– Includes output of another JSP file
● <jsp:plugin>
– Downloads Java plugin to browser to execute applet
or bean
10
What is a
Custom Tag?
11
What is a Custom Tag?
● User defined JSP language elements (as
opposed to standard tags)
● Encapsulates recurring tasks
● Distributed in a “custom made” tag library
12
Custom Tags Can
● Be customized via attributes passed from the
calling JSP page
● Pass variables back to the calling page
● Access all the objects available to JSP pages
● Communicate with each other
– You can create and initialize a JavaBeans
component, create a public EL variable that refers
to that bean in one tag, and then use the bean in
another tag
● Be nested within one another and
communicate via private variables
13
Custom Tag Examples
● Getting/setting Implicit objects
● Processing forms
● Accessing database
● Flow control
● Iterations
● Many more
14
Ready-to-usable Custom Tag
Library
● Java Standard Tag Library (JSTL)
– Tags for setting/getting attributes, iteration, etc
– Tags for database access
– Tags for internationalized formatting
– Tags for XML
● Jakarta-Taglibs
15
Why Custom Tags?
16
Why Custom Tags?
● Separate presentation from business (and
other functionality) logic
– page authors author presentation
– Business logic developers create custom tags
● Encapsulate business logic
– Reusable & Maintainable
● Help page authors
– Page authors use simpler syntax
● Provide
– Portable semantics
17
Custom Tags against JavaBeans
● Pros
– Custom tags can manipulate JSP contents
while beans cannot
– Complex operations can be reduced to a
significantly simpler form with custom tags than
beans
● Cons
– Custom tags require quite a bit of more work to
set up than do beans
19
Three things make up custom tag
architecture
● Tag handler class
– Defines tag's behavior
● Tag library descriptor (TLD)
– Maps XML elements to tag handler class
● JSP file (user of custom tags)
– Uses tags
20
Steps for implementing & using
& deploying custom tags
● Implementing custom tags
– Write tag handlers
– Write Tag library descriptor (TLD) file
– Package tag handlers and TLD file into tag
library (either unpacked or packed form)
● Using custom tags
– Write JSP pages that use tags
● Deploying custom tags as part of web app
– Configure and deploy tag library along with JSP
pages
21
Tag handler class
● Implements interface
– javax.servlet.jsp.tagext.Tag or
– javax.servlet.jsp.tagext.Bodytag interface
● Usually extends utility class
– javax.servlet.jsp.tagext.TagSupport or
– javax.servlet.jsp.tagext.BodyTagSupport class
● Located in the same directory as servlet
class files
– /WEB-INF/classes/<package-directory-structure>
22
Example: Tag Handler (page 1)
ExampleTag.java
package moreservlets.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
24
Tag Library Descriptor (TLD)
● XML file that describes
– tag name
– bodycontent
– attributes
– tag handler class
● Container knows which tag is associated
with which tag handler class via this file
● Located
– Usually under WEB-INF directory
● Custom location can specified in JSP file
– Via uri attribute of taglib directive 25
Example: TLD (page 1)
msajsp-tags.tld
<?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">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>msajsp-tags</shortname>
<info>
A tag library from More Servlets and JavaServer Pages,
http://www.moreservlets.com/.
</info>
26
Example: TLD (page 2)
msajsp-tags.tld
<tag>
<name>example</name>
<tagclass>moreservlets.tags.ExampleTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Simplest example: inserts one line of output</info>
</tag>
<tag>
<name>simplePrime</name>
<tagclass>moreservlets.tags.SimplePrimeTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Outputs a random 50-digit prime.</info>
</tag>
...
</taglib>
27
What is Tag Library?
● Is a collection of related tags
– Tag(s) can be packaged in a Tag Library
● Typically packaged as a jar file containing
– A tag library descriptor (TLD)
• e.g. META-INF/taglib.tld
– *.class files for the tag handler class(es)
– Any additional associated resource(s)
28
JSP page
● Declare the tag library via taglib directive
● Use tags using custom tag syntax
29
Declaring a tag library
● Include taglib directive before tags are used
● Syntax
– <%@ taglib prefix="myprefix" uri=”myuri” %>
– prefix: identifies the tag library
– uri: uniquely identifies the tag library descriptor
(TLD) directly or indirectly
30
Custom Tag Syntax in a JSP page
<prefix:tag attr1="value" ... attrN="value" />
or
<prefix:tag attr1="value" ... attrN="value" >
body
</prefix:tag>
31
Example: JSP page SimpleExample.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of very simple JSP custom tag.
33
How to build, configure
and deploy tag library
34
Source Directory Structure
● Use the following source directory structure (as in
J2EE 1.4 Tutorial's web/iterator directory)
– <j2ee14tutorial-install>/j2eetutorial14/examples/web
● iterator
● *.tld
● *.jsp
35
Build Directory Structure
(under build or dist directory)
● Use the following build directory structure (as in
J2EE 1.4 Tutorial's web/iterator directory)
– <j2eetutorial14-install>/j2eetutorial14/examples/web
● iterator
36
Usage Scenarios
of Custom Tags
(in JSP 1.2)
37
Usage Scenarios of Custom Tags
● Defining a basic tag
– A tag without attributes or tag bodies
● Assigning attributes to tags
● Including tag body
● Optionally including tag body
● Manipulating tag body
● Including or manipulating tag body multiple
times
● Using nested tags
38
Usage Scenarios of Custom Tags
● Bundling listeners with tag libraries
● Checking syntax with TagLibraryValidator
● Handling Exceptions with TryCatchFinally
interface
● Looping without generating BodyContent
39
Defining a basic tag
(We already saw
an example.)
40
Defining a basic tag
● A tag without attributes or body
● Extend TagSupport class
● All you have to do is to override doStartTag
() method
– doStartTag() method defines code that gets called
at request time at the place where the element's
start tag is found
– doStartTag() returns SKIP_BODY since the tag
does not have a body
● It instructs the container to ignore any body content
between start and end tags
41
Assigning attributes
to tags
42
Why assigning attributes to tags?
● Provides a way to pass attribute/value pairs
from JSP pages to custom tag handlers
● Custom tag handlers can use them in
whatever business logic they have
43
Tag handler class
● Use of an attribute X in a JSP page results in
a call to a method setX() in the tag handler
class
– Tag handler must implement setX() method
44
Example: Tag Handler (page 1)
SimplePrimeTag.java
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.math.*;
import moreservlets.*;
45
Example: Tag Handler (page 2)
SimplePrimeTag.java
public class SimplePrimeTag extends TagSupport {
protected int len = 50;
46
Example: Tag Handler (page 3)
PrimeTag.java
package moreservlets.tags;
47
Example: Tag Handler (page 4)
PrimeTag.java
public class PrimeTag extends SimplePrimeTag {
public void setLength(String length) {
try {
len = Integer.parseInt(length);
} catch(NumberFormatException nfe) {
len = 50;
}
}
49
TLD: Attribute's rtexprvalue/type
subelements
● rtexprvalue (optional)
– true if attribute value can be <%= expression %>
● attribute value can be determined at request time
– false if attribute value is a fixed string (default)
● type (optional)
– specifies the class to which the value of the
rtexprvalue should be typecast
– only legal when rtexprvalue is set to true
50
Example: TLD (page 1)
<?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">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>msajsp-tags</shortname>
<info>
A tag library from More Servlets and JavaServer Pages,
http://www.moreservlets.com/.
</info>
51
Example: TLD (page 2)
...
<tag>
<name>prime</name>
<tagclass>moreservlets.tags.PrimeTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Outputs a random N-digit prime.</info>
<attribute>
<name>length</name>
<required>false</required>
</attribute>
</tag>
...
</taglib>
52
Example: JSP Page (PrimeExample.jsp)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- Illustration of PrimeTag tag.
Taken from More Servlets and JavaServer Pages from Prentice Hall and Sun Microsystems
Press, http://www.moreservlets.com/.(C) 2002 Marty Hall; may be freely used or adapted.
-->
<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 uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>
<UL>
<LI>20-digit: <msajsp:prime length="20" />
<LI>40-digit: <msajsp:prime length="40" />
<LI>60-digit: <msajsp:prime length="60" />
<LI>Default (50-digit): <msajsp:prime />
</UL>
</BODY>
</HTML> 53
Example: Accessing PrimeExample.jsp
54
Including Tag Body
55
Including Tag body
● <prefix:tagname>body</prefix:tagname>
● Body content contains typical JSP constructs
● JSP constructs inside of body content get
translated at page translation time
● In this usage pattern, we are just including
body content without any modification
56
Tag handler class
● doStartTag() method should return
EVAL_BODY_INCLUDE
● doEndTag() gets called after body is
evaluated
– return EVAL_PAGE for continued processing
– return SKIP_PAGE for aborting processing rest of
the page
57
Example: Tag Handler (page 1)
HeadingTag.java
package moreservlets.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
... 59
Example: Tag Handler (page 3)
HeadingTag.java
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print("<TABLE BORDER=" + border +
" BGCOLOR=\"" + bgColor + "\"" + " ALIGN=\"" + align + "\"");
if (width != null) {
out.print(" WIDTH=\"" + width + "\"");
}
out.print("><TR><TH>");
out.print("<SPAN STYLE=\"" +
"font-size: " + fontSize + "px; " + "font-family: " + fontList + "; ");
if (color != null) {
out.println("color: " + color + ";");
}
out.print("\"> "); // End of <SPAN ...>
} catch(IOException ioe) {
System.out.println("Error in HeadingTag: " + ioe);
}
return(EVAL_BODY_INCLUDE); // Include tag body
60
}
Example: Tag Handler (page 4)
HeadingTag.java
public int doEndTag() {
try {
JspWriter out = pageContext.getOut();
out.print("</SPAN></TABLE>");
} catch(IOException ioe) {
System.out.println("Error in HeadingTag: " + ioe);
}
return(EVAL_PAGE); // Continue with rest of JSP page
}
}
61
TLD
● The bodycontent element should contain the
value JSP
– <bodycontent>JSP</bodycontent>
62
Example: TLD
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE ...>
<taglib>
...
<tag>
<name>heading</name>
<tagclass>moreservlets.tags.HeadingTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Outputs a 1-cell table used as a heading.</info>
<attribute>
<name>bgColor</name>
<required>true</required> <!-- bgColor is required -->
</attribute>
<attribute>
<name>color</name>
<required>false</required>
</attribute>
... 63
Example: JSP Page (HeadingExample.jsp)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of HeadingTag tag.
65
66
Optionally
Including Tag Body
67
Optionally Including Tag body
● Decision of usage of body content is decided
at request time
● Body content is not modified
68
Tag handler class
● doStartTag() method returns either
EVAL_BODY_INCLUDE or SKIP_BODY
– depending on the value of some request time
expression, for example
● Call getRequest() from pageContext field of
TagSupport
– Typecast the return of getRequest() to
HttpServletRequest since getRequest() returns
ServletRequest type
69
Example: Tag Handler (page 1)
DebugTag.java
package moreservlets.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;
70
Example: Tag Handler (page 2)
DebugTag.java
public class DebugTag extends TagSupport {
public int doStartTag() {
ServletRequest request = pageContext.getRequest();
String debugFlag = request.getParameter("debug");
if ((debugFlag != null) &&
(!debugFlag.equalsIgnoreCase("false"))) {
return(EVAL_BODY_INCLUDE);
} else {
return(SKIP_BODY);
}
}
}
71
Example: TLD
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE ...>
<taglib>
...
<tag>
<name>debug</name>
<tagclass>moreservlets.tags.DebugTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Includes body only if debug param is set.</info>
</tag>
...
72
Example: JSP Page (DebugExample.jsp)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of DebugTag tag.
73
Example: JSP Page (DebugExample.jsp)
<msajsp:debug>
<B>Debug:</B>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Requesting hostname: <%= request.getRemoteHost() %>
<LI>Session ID: <%= session.getId() %>
</UL>
</msajsp:debug>
<P>
Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
</BODY>
</HTML>
74
DebugTag without “debug” input
parameter
75
Accessing DebugExample.jsp with
“debug=true” input param
76
Manipulating Tag Body
77
Tag handler class
● Tag handler class should extend
BodyTagSupport class
● BodyTagSupport class has 2 convenience
methods
– doAfterBody(): override this method in order to
manipulate the tag body
● return SKIP_BODY if no further body processing is needed
● return EVAL_BODY_TAG (JSP 1.1) or
EVAL_BODY_AGAIN (JSP 1.2) if the body content needs
to be evaluated and handled again
– getBodyContent(): returns BodyContent object
78
BodyContent class
● An encapsulation of the evaluation of the
body
● A subclass of JspWriter
● BodyContent class has 3 methods
– getEnclosingWriter(): returns JspWriter
– getReader(): returns a Reader that can read tag
body
– getString(): returns a String containing entire tag
body
79
Example: Tag Handler (page 1)
FilterTag.java
package moreservlets.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import moreservlets.*;
/** A tag that replaces <, >, ", and & with their HTML
* character entities (<, >, ", and &).
* After filtering, arbitrary strings can be placed
* in either the page body or in HTML attributes.
* <P>
* Taken from More Servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* http://www.moreservlets.com/.
* © 2002 Marty Hall; may be freely used or adapted.
*/
80
Example: Tag Handler (page 2)
FilterTag.java
public class FilterTag extends BodyTagSupport {
public int doAfterBody() {
BodyContent body = getBodyContent();
String filteredBody =
ServletUtilities.filter(body.getString());
try {
JspWriter out = body.getEnclosingWriter();
out.print(filteredBody);
} catch(IOException ioe) {
System.out.println("Error in FilterTag: " + ioe);
}
// SKIP_BODY means we're done. If we wanted to evaluate
// and handle the body again, we'd return EVAL_BODY_TAG
// (JSP 1.1/1.2) or EVAL_BODY_AGAIN (JSP 1.2 only)
return(SKIP_BODY);
}
}
81
Example: TLD
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE ...>
<taglib>
...
<tag>
<name>filter</name>
<tagclass>moreservlets.tags.FilterTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Replaces HTML-specific characters in body.</info>
</tag>
...
82
Example: JSP Page (FilterExample.jsp)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of FilterTag tag.
85
Including or Manipulating
Tag Body Multiple Times
86
Tag handler class
● Tag handler class should extend
BodyTagSupport class
● doAfterBody() now returns
EVAL_BODY_TAG (EVAL_BODY_AGAIN in
JSP 1.2)
87
Example: Tag Handler (page 1)
RepeatTag.java
package moreservlets.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
88
Example: Tag Handler (page 2)
RepeatTag.java
public class RepeatTag extends BodyTagSupport {
private int reps;
89
Example: Tag Handler (page 3)
RepeatTag.java
public int doAfterBody() {
if (reps-- >= 1) {
BodyContent body = getBodyContent();
try {
JspWriter out = body.getEnclosingWriter();
out.println(body.getString());
body.clearBody(); // Clear for next evaluation
} catch(IOException ioe) {
System.out.println("Error in RepeatTag: " + ioe);
}
// Replace EVAL_BODY_TAG with EVAL_BODY_AGAIN in JSP 1.2.
return(EVAL_BODY_TAG);
} else {
return(SKIP_BODY);
}
}
90
Example: TLD
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE ...>
<taglib>
...
<tag>
<name>repeat</name>
<tagclass>moreservlets.tags.RepeatTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Repeats body the specified number of times.</info>
<attribute>
<name>reps</name>
<required>true</required>
<!-- rtexprvalue indicates whether attribute
can be a JSP expression. -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
... 91
Example: JSP Page (RepeatExample.jsp)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of RepeatTag tag.
92
Example: JSP Page (RepeatExample.jsp)
<%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>
<OL>
<!-- Repeats N times. A null reps value means repeat once. -->
<msajsp:repeat reps='<%= request.getParameter("repeats") %>'>
<LI><msajsp:prime length="40" />
</msajsp:repeat>
</OL>
</BODY>
</HTML>
93
To be added
94
More detailed information
on How to declare tag
library using taglib directive
95
Declaring a tag library: uri attribute
(3 different ways - 2 on this slide)
● Direct reference to TLD file
– <%@ taglib prefix="tlt" uri="/WEB-INF/iterator.tld"%>
● Indirect reference to TLD file using a logical
name
– <%@ taglib prefix="tlt" uri="/tlt"%>
– Mapping of the logical name to path to the TLD file
has to be defined in web.xml
<jsp-config>
<taglib>
<taglib-uri>/tlt</taglib-uri>
<taglib-location>/WEB-INF/iterator.tld</taglib-location>
</taglib>
</jsp-config>
96
Declaring a tag library: uri attribute
(3 different ways - 1 on this slide)
● Absolute URI - examples of JSTL tag libraries
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="xml" uri="http://java.sun.com/jsp/jstl/xml"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
97
More detailed information on
How to Configure tag library
with Web application
98
Configuring tag library with
individual Web app
● In unpacked form
– tag handler classes are packaged under
the /WEB-INF/classes/ directory
– *.tld file under the /WEB-INF/ directory
● In packaged form (*.jar file)
– *.jar file is in the /WEB-INF/lib/ directory
99
How does it Work?
100
How does it work?
● JSP translator locates the TLD file via uri
attribute of taglib directive
– The TLD file describes the binding between an
action (tag handler) and a Tag
● Using a tag in a JSP page generates the
appropriate servlet code
– The servlet code contains tag handler
101
Sequence of Calls from Container
102
TagSupport Implements Tag
Interface
103
doStartTag() and doEndTag()
● doStartTag()
– Processes starting element (semantics)
– Returns EVAL_BODY_INCLUDE to process body
– Returns SKIP_BODY to skip body
● doEndTag()
– Completes element processing (flush)
– Returns EVAL_PAGE to continue processing
– Returns SKIP_PAGE to terminate processing
● Both can throw JspException
104
Calling Sequence from the Container
Obtain
Obtain Set
Setproperties
properties Set
Setattribute
attribute
setPageContext( )
handler
handler setParent( )
values
values
Eval_body_include
doStartTag( )
Process
Processbody
body
Skip_body
Skip_page Eval_page
doEndTag( )
Release(
Release()) Release(
Release() )
Continue
Continue
Stop
105
How Is a Tag Invoked?
● JSP technology creates (or reuses) a Tag class instance
associated with the element in the page source
– Class is named in the TLD
● Container calls setPageContext() and setParent()
– parent (possibly null, unless nested)
– PageContext provides access to: request, response,
out, session, page and attributes
● Container calls setX() methods for attributes specified
● Container calls doStartTag() and doEndTag()
● Container invokes release() to free Tag instance for
reuse
106
How Is a Tag Invoked?
setPageContext()
setParent()
• setAttr1(“values1”)
<prefix:actionName
attr1=“value1” • setAttr2(“value2”)
attr2=“value2”
> • doStartTag( )
• doInitBody( )
</prefix:actionName>
• doAfterBody( )
• doEndTag( )
107
JSP Page Response Output
● The output of the page is written into a
JSPWriter provided by the page implementation
● This is flushed to the output stream of the
ServletResponse.
● Output is buffered in the JSPWriter by default.
● Tags output to nested JSPWriter streams.
108
BodyTag, BodyTagSupport
• For manipulating or evaluating body multiple times,
use BodyTagSupport which is BodyTag type
• Example of iteration:
– such as order rows, search results and etc
109
How Does BodyTag Work?
110
BodyContent
111
Manipulating BodyContent (1)
● JSP technology creates a nested stream
(BodyContent) to contain the body text
● The BodyContent is passed to the
BodyTag via setBodyContent()
● doStartBody() is invoked
● doInitBody() is invoked
● The body text is evaluated into the
BodyContent
112
Manipulating BodyContent (2)
● doAfterBody() is invoked:
– It must process the content of the nested stream and
write to nesting stream (out)
– It can cause the page to be re-evaluated (to support
iterative tags) by returning EVAL_BODY_TAG
● Invoke doEndTag().
113
BodyTag Method Semantics
● doStartTag():
– Same as Tag semantic, except:
• Returns EVAL_BODY_TAG to process body
● doBodyInit():
– Prepare to process body
● doAfterBody() :
– Handle processed body in BodyContent
– Return EVAL_BODY_TAG to reprocess
● DoEndTag() :
– Same as Tag Semantics
114
Passion!
115