Title: JSP 1.2
1JSP 1.2 Custom Tags
2Agenda
- What is and why custom tags?
- Components that make up custom tag architecture
- How to create custom tags?
- How does it work?
- JSTL
3Evolution of Web tier technology
4Web Application Designs
5Standard Action Tags
- ltjspuseBeangt
- Instantiate Java Bean class without explicit Java
programming language - ltjspgetPropertygt
- Allow accessing bean properties
- ltjspsetPropertygt
- Allow setting bean properties
6Standard Action Tags
- ltjspforwardgt
- Forwards request to HTML page, JSP, or servlet
- ltjspincludegt
- Includes data in a JSP page from another file
- ltjspplugingt
- Downloads Java plugin to browser to execute
applet or bean
7What is Custom Tag?
8What is a Custom Tag?
- User defined JSP language elements
- Encapsulates recurring tasks
- Distributed in a custom made tag library
9Custom Tag Features
- Be customized via attributes passed from the
calling 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
10Custom Tag Examples
- Getting/setting Implicit objects
- Accessing database
- Flow control
- Iterations
- Many more
11Ready-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
12Why Custom Tags?
13Why Custom Tags?
- Separate JSP page content from business (and
other functionality) logic - Encapsulate business logic
- Reusable Maintainable
- Easier to
- author manually and to be manipulated by tool
- Provide
- Portable semantics
14Custom Tags vs. JavaBeans
- Custom tags can manipulate JSP contents while
beans cannot - Complex operations can be reduced to a
significantly simpler form with custom tags than
the beans - Custom tags require quite a bit of more work to
set up than do beans
15Quick Introduction on Components that make up
Custom tag architecture
16Three things make up custom tagarchitetecture
- Tag handler class
- Defines tag's behavior
- Tag library descriptor (TLD)
- Maps XML elements to tag handler class
- JSP file
- Uses tags
17Steps for implementing custom tags
- Write tag handlers
- Write Tag library descriptor (TLD) file
- Write JSP pages that use tags
18Tag handler class
- Implements
- javax.servlet.jsp.tagext.Tag or
- javax.servlet.jsp.tagext.Bodytag interface
- Usually extends
- javax.servlet.jsp.tagext.TagSupport or
- javax.servlet.jsp.tagext.BodyTagSupport class
- Located in the same directory as servlet class
files - /WEB-INF/classes/ltpackage-directory-structuregt
19Example Tag Handler (page 1)ExampleTag.java
- package moreservlets.tags
- import javax.servlet.jsp.
- import javax.servlet.jsp.tagext.
- import java.io.
- / Very simple JSP tag that just inserts a
string - ("Custom tag example...") into the output.
- The actual name of the tag is not defined
here - that is given by the Tag Library Descriptor
(TLD) - file that is referenced by the taglib
directive - in the JSP file.
- ltPgt
- Taken from More Servlets and JavaServer Pages
- from Prentice Hall and Sun Microsystems
Press, - http//www.moreservlets.com/.
- copy 2002 Marty Hall may be freely used or
adapted. /
20Example Tag Handler (page 2)ExampleTag.java
- public class ExampleTag extends TagSupport
- public int doStartTag()
- try
- JspWriter out pageContext.getOut()
- out.print("Custom tag example "
- "(moreservlets.tags.ExampleTag)")
- catch(IOException ioe)
- System.out.println("Error in ExampleTag "
ioe) -
- return(SKIP_BODY)
-
21Tag 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
- Location specified in JSP file
- Via uri attribute of taglib directive
22Example TLD (page 1 ) msajsp-tags.tld
- lt?xml version"1.0" encoding"ISO-8859-1" ?gt
- lt!DOCTYPE taglib
- PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag
Library 1.1//EN" - "http//java.sun.com/j2ee/dtds/web-jsptaglibrary_
1_1.dtd"gt - lt!-- a tag library descriptor --gt
- lttaglibgt
- lttlibversiongt1.0lt/tlibversiongt
- ltjspversiongt1.1lt/jspversiongt
- ltshortnamegtmsajsp-tagslt/shortnamegt
- ltinfogt
- A tag library from More Servlets and
JavaServer Pages, - http//www.moreservlets.com/.
- lt/infogt
23Example TLD (page 2) msajsp-tags.tld
- lttaggt
- ltnamegtexamplelt/namegt
- lttagclassgtmoreservlets.tags.ExampleTaglt/tagcla
ssgt - ltbodycontentgtemptylt/bodycontentgt
- ltinfogtSimplest example inserts one line of
outputlt/infogt - lt/taggt
- lttaggt
- ltnamegtsimplePrimelt/namegt
lttagclassgtmoreservlets.tags.SimplePrimeTaglt/tagcla
ssgt - ltbodycontentgtemptylt/bodycontentgt
- ltinfogtOutputs a random 50-digit prime.lt/infogt
- lt/taggt
- ...
- lt/taglibgt
24JSP page
- Declare the tag library via taglib directive
- Use tags using custom tag syntax
25Declaring a tag library
- Include taglib directive before tags are used
- Syntax
- lt_at_ taglib prefix"myprefix" urimyuri gt
- prefix identifies the tag library
- uri uniquely identifies the tag library
descriptor (TLD) directly or indirectly
26Custom Tag Syntax in JSP page
- ltprefixtag attr1"value" ... attrN"value" /gt
- or
- ltprefixtag attr1"value" ... attrN"value" gt
- body
- lt/prefixtaggt
- prefix distinguishes tag library
- tag identifies a tag (within the tag library)
- attr1 ... attrN modify the behavior of the tag
27Example JSP page SimpleExample.jsp
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lt!--
- Illustration of very simple JSP custom 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. - --gt
- ltHTMLgt
- ltHEADgt
- lt_at_ taglib uri"/WEB-INF/msajsp-taglib.tld"
prefix"msajsp" gt - ltTITLEgtltmsajspexample /gtlt/TITLEgt
- ltLINK RELSTYLESHEET
- HREF"JSP-Styles.css"
- TYPE"text/css"gt
- lt/HEADgt
- ltBODYgt
- ltH1gtltmsajspexample /gtlt/H1gt
28Example Accessing SimpleExample.jsp
29Sample codes we will use in this class
30Usage Scenarios of Custom Tags
31Usage Scenarios of Custom Tags(Common between
JSP 1.1 and 1.2)
- 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
32Defining a basic tag
33Defining 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
34Assigning attributes to tags
35Why 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
36Tag 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
- public void setX(String value1)
- doSomethingWith(value1)
37Example Tag Handler (page 1) SimplePrimeTag.java
- import javax.servlet.jsp.
- import javax.servlet.jsp.tagext.
- import java.io.
- import java.math.
- import moreservlets.
- / Generates a prime of approximately 50 digits.
- (50 is actually the length of the random
number - generated -- the first prime above that
number will - be returned.)
- ltPgt
- Taken from More Servlets and JavaServer Pages
- from Prentice Hall and Sun Microsystems
Press, - http//www.moreservlets.com/.
- copy 2002 Marty Hall may be freely used or
adapted. - /
38Example Tag Handler (page 2) SimplePrimeTag.java
- public class SimplePrimeTag extends TagSupport
- protected int len 50
-
- public int doStartTag()
- try
- JspWriter out pageContext.getOut()
- BigInteger prime Primes.nextPrime(Primes.r
andom(len)) - out.print(prime)
- catch(IOException ioe)
- System.out.println("Error generating prime
" ioe) -
- return(SKIP_BODY)
-
-
39Example Tag Handler (page 3) PrimeTag.java
- package moreservlets.tags
- / Generates an N-digit random prime (default N
50). - Extends SimplePrimeTag, adding a length
attribute - to set the size of the prime. The doStartTag
- method of the parent class uses the len field
- to determine the length of the prime.
- ltPgt
- Taken from More Servlets and JavaServer Pages
- from Prentice Hall and Sun Microsystems
Press, - http//www.moreservlets.com/.
- copy 2002 Marty Hall may be freely used or
adapted. - /
40Example 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
-
-
- / Servers are permitted to reuse tag
instances - once a request is finished. So, this resets
- the len field.
- /
- public void release()
- len 50
-
41TLD
- Attributes must be declared inside tag element by
means of attribute sub-elements - Attribute element has 5 sub-elements of its own
- name (required)
- required (required)
- rtexprvalue (optional)
- type (optional)
- example (optional)
42TLD Attribute's rtexprvalue/type subelements
- rtexprvalue (optional)
- true if attribute value can be lt expression gt
- 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
43Example TLD (page 1)
- lt?xml version"1.0" encoding"ISO-8859-1" ?gt
- lt!DOCTYPE taglib
- PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag
Library 1.1//EN" - "http//java.sun.com/j2ee/dtds/web-jsptaglibrary_
1_1.dtd"gt - lt!-- a tag library descriptor --gt
- lttaglibgt
- lttlibversiongt1.0lt/tlibversiongt
- ltjspversiongt1.1lt/jspversiongt
- ltshortnamegtmsajsp-tagslt/shortnamegt
- ltinfogt
- A tag library from More Servlets and
JavaServer Pages, - http//www.moreservlets.com/.
- lt/infogt
44Example TLD (page 2)
- ...
- lttaggt
- ltnamegtprimelt/namegt
- lttagclassgtmoreservlets.tags.PrimeTaglt/tagclass
gt - ltbodycontentgtemptylt/bodycontentgt
- ltinfogtOutputs a random N-digit prime.lt/infogt
- ltattributegt
- ltnamegtlengthlt/namegt
- ltrequiredgtfalselt/requiredgt
- lt/attributegt
- lt/taggt
- ...
- lt/taglibgt
45Example JSP Page (PrimeExample.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lt!-- 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. - --gt
- ltHTMLgt
- ltHEADgt
- ltTITLEgtSome N-Digit Primeslt/TITLEgt
- ltLINK RELSTYLESHEET
- HREF"JSP-Styles.css"
- TYPE"text/css"gt
- lt/HEADgt
- ltBODYgt
- ltH1gtSome N-Digit Primeslt/H1gt
- lt_at_ taglib uri"/WEB-INF/msajsp-taglib.tld"
prefix"msajsp" gt - ltULgt
- ltLIgt20-digit ltmsajspprime length"20" /gt
- ltLIgt40-digit ltmsajspprime length"40" /gt
- ltLIgt60-digit ltmsajspprime length"60" /gt
46Example Accessing PrimeExample.jsp
47Tag 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
48Example Tag Handler (page 1)HeadingTag.java
- package moreservlets.tags
- import javax.servlet.jsp.
- import javax.servlet.jsp.tagext.
- import java.io.
- / Generates an HTML heading with the specified
background - color, foreground color, alignment, font, and
font size. - You can also turn on a border around it,
which normally - just barely encloses the heading, but which
can also - stretch wider. All attributes except the
background - color are optional.
- ltPgt
- Taken from More Servlets and JavaServer Pages
- from Prentice Hall and Sun Microsystems
Press, - http//www.moreservlets.com/.
- copy 2002 Marty Hall may be freely used or
adapted. - /
49Example Tag Handler (page 2)HeadingTag.java
- public class HeadingTag extends TagSupport
- private String bgColor // The one required
attribute - private String color null
- private String align"CENTER"
- private String fontSize"36"
- private String fontList"Arial, Helvetica,
sans-serif" - private String border"0"
- private String widthnull
-
- public void setBgColor(String bgColor)
- this.bgColor bgColor
-
- public void setColor(String color)
- this.color color
-
- ...
50Example Tag Handler (page 3)HeadingTag.java
- public int doStartTag()
- try
- JspWriter out pageContext.getOut()
- out.print("ltTABLE BORDER" border
- " BGCOLOR\"" bgColor
"\"" " ALIGN\"" align "\"") - if (width ! null)
- out.print(" WIDTH\"" width "\"")
-
- out.print("gtltTRgtltTHgt")
- out.print("ltSPAN STYLE\""
- "font-size " fontSize "px "
"font-family " fontList " ") - if (color ! null)
- out.println("color " color "")
-
- out.print("\"gt ") // End of ltSPAN ...gt
- catch(IOException ioe)
- System.out.println("Error in HeadingTag "
ioe) -
- return(EVAL_BODY_INCLUDE) // Include tag
body
51Example Tag Handler (page 4)HeadingTag.java
- public int doEndTag()
- try
- JspWriter out pageContext.getOut()
- out.print("lt/SPANgtlt/TABLEgt")
- catch(IOException ioe)
- System.out.println("Error in HeadingTag "
ioe) -
- return(EVAL_PAGE) // Continue with rest of
JSP page -
-
52TLD
- The bodycontent element should contain the value
JSP - ltbodycontentgtJSPlt/bodycontentgt
53Example TLD
- lt?xml version"1.0" encoding"ISO-8859-1" ?gt
- lt!DOCTYPE ...gt
- lttaglibgt
- ...
- lttaggt
- ltnamegtheadinglt/namegt
- lttagclassgtmoreservlets.tags.HeadingTaglt/tagcla
ssgt - ltbodycontentgtJSPlt/bodycontentgt
- ltinfogtOutputs a 1-cell table used as a
heading.lt/infogt - ltattributegt
- ltnamegtbgColorlt/namegt
- ltrequiredgttruelt/requiredgt lt!-- bgColor is
required --gt - lt/attributegt
- ltattributegt
- ltnamegtcolorlt/namegt
- ltrequiredgtfalselt/requiredgt
- lt/attributegt ...
54Example JSP Page (HeadingExample.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lt!--
- Illustration of HeadingTag 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. - --gt
- ltHTMLgt
- ltHEADgt
- ltTITLEgtSome Tag-Generated Headingslt/TITLEgt
- lt/HEADgt
- ltBODYgt
- lt_at_ taglib uri"/WEB-INF/msajsp-taglib.tld"
prefix"msajsp" gt - ltmsajspheading bgColor"C0C0C0"gt
- Default Heading
- lt/msajspheadinggt
- ltPgt
55Example JSP Page (HeadingExample.jsp)
- ltPgt
- ltmsajspheading bgColor"EF8429" fontSize"60"
border"5"gt - Large Bordered Heading
- lt/msajspheadinggt
- ltPgt
- ltmsajspheading bgColor"CYAN" width"100"gt
- Heading with Full-Width Background
- lt/msajspheadinggt
- ltPgt
- ltmsajspheading bgColor"CYAN" fontSize"60"
- fontList"Brush Script MT, Times,
serif"gt - Heading with Non-Standard Font
- lt/msajspheadinggt
- lt/BODYgt
- lt/HTMLgt
56(No Transcript)
57Optionally Including Tag Body
58Optionally Including Tag body
- Decision of usage of body content is decided at
request time - Body content is not modified
59Tag 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
60Example Tag Handler (page 1)DebugTag.java
- package moreservlets.tags
- import javax.servlet.jsp.
- import javax.servlet.jsp.tagext.
- import java.io.
- import javax.servlet.
- / A tag that includes the body content only if
- the "debug" request parameter is set.
- ltPgt
- Taken from More Servlets and JavaServer Pages
- from Prentice Hall and Sun Microsystems
Press, - http//www.moreservlets.com/.
- copy 2002 Marty Hall may be freely used or
adapted. - /
61Example Tag Handler (page 2)DebugTag.java
- public class DebugTag extends TagSupport
- public int doStartTag()
- ServletRequest request pageContext.getReques
t() - String debugFlag request.getParameter("debug
") - if ((debugFlag ! null)
- (!debugFlag.equalsIgnoreCase("false")))
- return(EVAL_BODY_INCLUDE)
- else
- return(SKIP_BODY)
-
-
62Example TLD
- lt?xml version"1.0" encoding"ISO-8859-1" ?gt
- lt!DOCTYPE ...gt
- lttaglibgt
- ...
- lttaggt
- ltnamegtdebuglt/namegt
- lttagclassgtmoreservlets.tags.DebugTaglt/tagclass
gt - ltbodycontentgtJSPlt/bodycontentgt
- ltinfogtIncludes body only if debug param is
set.lt/infogt - lt/taggt
- ...
63Example JSP Page (DebugExample.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lt!--
- Illustration of DebugTag 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. - --gt
- ltHTMLgt
- ltHEADgt
- ltTITLEgtUsing the Debug Taglt/TITLEgt
- ltLINK RELSTYLESHEET
- HREF"JSP-Styles.css"
- TYPE"text/css"gt
- lt/HEADgt
- ltBODYgt
- ltH1gtUsing the Debug Taglt/H1gt
- lt_at_ taglib uri"/WEB-INF/msajsp-taglib.tld"
prefix"msajsp" gt
64Example JSP Page (DebugExample.jsp)
- ltmsajspdebuggt
- ltBgtDebuglt/Bgt
- ltULgt
- ltLIgtCurrent time lt new java.util.Date() gt
- ltLIgtRequesting hostname lt request.getRemoteHo
st() gt - ltLIgtSession ID lt session.getId() gt
- lt/ULgt
- lt/msajspdebuggt
- ltPgt
- Bottom of regular page. Blah, blah, blah. Yadda,
yadda, yadda. - lt/BODYgt
- lt/HTMLgt
65DebugTag without debug inputparameter
66Accessing DebugExample.jsp with debugtrue
input param
67Manipulating Tag Body
68Tag 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
69BodyContent 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
70Example 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 lt, gt, ", and with their
HTML - character entities (lt, gt, quot, and
amp). - After filtering, arbitrary strings can be
placed - in either the page body or in HTML
attributes. - ltPgt
- Taken from More Servlets and JavaServer Pages
- from Prentice Hall and Sun Microsystems
Press, - http//www.moreservlets.com/.
- copy 2002 Marty Hall may be freely used or
adapted. - /
71Example 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)
-
72Example TLD
- lt?xml version"1.0" encoding"ISO-8859-1" ?gt
- lt!DOCTYPE ...gt
- lttaglibgt
- ...
- lttaggt
- ltnamegtfilterlt/namegt
- lttagclassgtmoreservlets.tags.FilterTaglt/tagclas
sgt - ltbodycontentgtJSPlt/bodycontentgt
- ltinfogtReplaces HTML-specific characters in
body.lt/infogt - lt/taggt
- ...
73Example JSP Page (FilterExample.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lt!--
- Illustration of FilterTag 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.--gt - ltHTMLgt
- ltHEADgt
- ltTITLEgtHTML Logical Character Styleslt/TITLEgt
- ltLINK RELSTYLESHEET
- HREF"JSP-Styles.css"
- TYPE"text/css"gt
- lt/HEADgt
- ltBODYgt
- ltH1gtHTML Logical Character Styleslt/H1gt
- Physical character styles (B, I, etc.) are
rendered consistently - in different browsers. Logical character styles,
however, - may be rendered differently by different
browsers.
74Example JSP Page (FilterExample.jsp)
- lt_at_ taglib uri"/WEB-INF/msajsp-taglib.tld"
prefix"msajsp" gt - ltTABLE BORDER1 ALIGN"CENTER"gt
- ltTR CLASS"COLORED"gtltTHgtExampleltTHgtResult
- ltTRgt
- ltTDgtltPREgtltmsajspfiltergt
- ltEMgtSome emphasized text.lt/EMgtltBRgt
- ltSTRONGgtSome strongly emphasized
text.lt/STRONGgtltBRgt - ltCODEgtSome code.lt/CODEgtltBRgt
- ltSAMPgtSome sample text.lt/SAMPgtltBRgt
- ltKBDgtSome keyboard text.lt/KBDgtltBRgt
- ltDFNgtA term being defined.lt/DFNgtltBRgt
- ltVARgtA variable.lt/VARgtltBRgt
- ltCITEgtA citation or reference.lt/CITEgt
- lt/msajspfiltergtlt/PREgt
- ltTDgt
- ltEMgtSome emphasized text.lt/EMgtltBRgt
- ltSTRONGgtSome strongly emphasized
text.lt/STRONGgtltBRgt - ltCODEgtSome code.lt/CODEgtltBRgt
- ltSAMPgtSome sample text.lt/SAMPgtltBRgt
75To be added
76Including or Manipulating Tag Body Multiple Times
77Tag handler class
- Tag handler class should extend BodyTagSupport
class - doAfterBody() now returns EVAL_BODY_TAG
(EVAL_BODY_AGAIN in JSP 1.2)
78Example Tag Handler (page 1)RepeatTag.java
- package moreservlets.tags
- import javax.servlet.jsp.
- import javax.servlet.jsp.tagext.
- import java.io.
- / A tag that repeats the body the specified
- number of times.
- ltPgt
- Taken from More Servlets and JavaServer Pages
- from Prentice Hall and Sun Microsystems
Press, - http//www.moreservlets.com/.
- copy 2002 Marty Hall may be freely used or
adapted. - /
79Example Tag Handler (page 2)RepeatTag.java
public class RepeatTag extends BodyTagSupport
private int reps public void setReps(String
repeats) try reps
Integer.parseInt(repeats)
catch(NumberFormatException nfe) reps
1
80Example Tag Handler (page 3)RepeatTag.java
public int doAfterBody() if (reps-- gt 1)
BodyContent body getBodyContent()
try JspWriter out body.getEnclosingWr
iter() 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)
81Example TLD
- lt?xml version"1.0" encoding"ISO-8859-1" ?gt
- lt!DOCTYPE ...gt
- lttaglibgt ...
- lttaggt
- ltnamegtrepeatlt/namegt
- lttagclassgtmoreservlets.tags.RepeatTaglt/tagclas
sgt - ltbodycontentgtJSPlt/bodycontentgt
- ltinfogtRepeats body the specified number of
times.lt/infogt - ltattributegt
- ltnamegtrepslt/namegt
- ltrequiredgttruelt/requiredgt
- lt!-- rtexprvalue indicates whether
attribute - can be a JSP expression. --gt
- ltrtexprvaluegttruelt/rtexprvaluegt
- lt/attributegt
- lt/taggt
- ...
82Example JSP Page (RepeatExample.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lt!--
- Illustration of RepeatTag 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. - --gt
- ltHTMLgt
- ltHEADgt
- ltTITLEgtSome 40-Digit Primeslt/TITLEgt
- ltLINK RELSTYLESHEET
- HREF"JSP-Styles.css"
- TYPE"text/css"gt
- lt/HEADgt
- ltBODYgt
- ltH1gtSome 40-Digit Primeslt/H1gt
- Each entry in the following list is the first
prime number
83Example JSP Page (RepeatExample.jsp)
- lt_at_ taglib uri"/WEB-INF/msajsp-taglib.tld"
prefix"msajsp" gt - ltOLgt
- lt!-- Repeats N times. A null reps value means
repeat once. --gt - ltmsajsprepeat reps'lt request.getParameter("rep
eats") gt'gt - ltLIgtltmsajspprime length"40" /gt
- lt/msajsprepeatgt
- lt/OLgt
- lt/BODYgt
- lt/HTMLgt
84To be added
85More detailed information on How to declare
tag library using taglib directive
86Declaring a tag library uri attribute(3
different ways - 2 on this slide)
- Direct reference to TLD file
- lt_at_ taglib prefix"tlt" uri"/WEB-INF/iterator.tld
"gt - Indirect reference to TLD file using a logical
name - lt_at_ taglib prefix"tlt" uri"/tlt"gt
- Mapping of the logical name to path to the TLD
file has to be defined in web.xml - ltjsp-configgt
- lttaglibgt
- lttaglib-urigt/tltlt/taglib-urigt
- lttaglib-locationgt/WEB-INF/iterator.tldlt/taglib
-locationgt - lt/taglibgt
- lt/jsp-configgt
87Declaring a tag library uri attribute(3
different ways - 1 on this slide)
- Absolute URI - examples of JSTL tag libraries
- lt_at_ taglib prefix"core" uri"http//java.sun.com/
jsp/jstl/core"gt - lt_at_ taglib prefix"xml" uri"http//java.sun.com/j
sp/jstl/xml"gt - lt_at_ taglib prefix"fmt" uri"http//java.sun.com/j
sp/jstl/fmt"gt - lt_at_ taglib prefix"sql" uri"http//java.sun.com/j
sp/jstl/sql"gt - lt_at_ taglib prefix"fn" uri"http//java.sun.com/js
p/jstl/functions"gt
88More detailed information on How to Configure tag
library with Web application
89Configuring 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
90Configuring tag library globally(for all Web
apps on a server)
- For Tomcat of Java WSDP
- Cove .jar file (tag library) to
ltJWSDP_HOMEgt/common/lib - Any jar files under ltJWSDP_HOMEgt/common/lib will
be available to all Web apps
91How does it Work?
92How 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
93Sequence of Calls from Container
94TagSupport Implements Tag Interface
95doStartTag() 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
96Calling Sequence from the Container
97How 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
98How Is a Tag Invoked?
setPageContext() setParent()
99JSP 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.
100BodyTag, 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
101How Does BodyTag Work?
102BodyContent
103Manipulating 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
104Manipulating 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().
105BodyTag 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
106What is JSTL?
- Standard set of tag libraries
- Encapsulates core functionality common to many
JSP applications - iteration, conditionals, XML, database access,
internationalized formatting
107Why JSTL?
- You don't have to write them yourself
- You learn and use a single standard set of tag
libraries that are already provided by compliant
Java platforms - Vendors are likely to provide more optimized
implementation - Portability of your applications are enabled
108JSTL Tag Libraries
- Core (prefix c)
- Variable support, Flow control, URL management
- XML (prefix x)
- Core, Flow control, Transformation
- Internationalization (i18n) (prefix fmt)
- Locale, Message formatting, Number and date
formatting - Database (prefix sql)
- SQL query and update
- Functions (prefix fn)
- Collection length, String manipulation
109Declaration of JSTL Tag Libraries
- Core
- lt_at_ taglib prefix"c" uri"http//java.sun.com/jsp
/jstl/core" gt - XML
- lt_at_ taglib prefix"x" uri"http//java.sun.com/jsp
/jstl/xml" gt - Internationalization (i18n)
- lt_at_ taglib prefix"fmt" uri"http//java.sun.com/j
sp/jstl/fmt" gt - Database (SQL)
- lt_at_ taglib prefix"sql" uri"http//java.sun.com/j
sp/jstl/sql" gt - Functions
- lt_at_ taglib prefix"fn" uri"http//java.sun.com/js
p/jstl/functions" gt
110JSTL Tag Library Jar Files
- Distributed as two jar files
- standard.jar
- jstl.jar
- Under JWSDP
- ltjwsdp-installgt/jstl/lib/standard.jar
- ltjwsdp-installgt/jstl/lib/jstl.jar
- How to configure them with your Web apps
- Load them automatically with every Web app
- copy them to ltjwsdp-installgt/common/lib
- Load them only with your app
- copy them to ltyour-app-rootgt/WEB-INF/lib
111Core Tags Types (page 1)
- Variable support
- ltcsetgt
- ltcremovegt
- Conditional
- ltcifgt
- ltcchoosegt
- ltcwhengt
- ltcotherwisegt
- Iteration
- ltcforEachgt
- ltcforTokensgt
112Core Tags Types (page 2)
- URL management
- ltcimportgt
- ltcparamgt
- ltcredirectgt
- ltcparamgt
- ltcurlgt
- ltcparamgt
- General purpose
- ltcoutgt
- ltccatchgt
113Variable Support, ltcsetgt
- Sets the value of an EL variable or the property
of an EL variable via var attribute in any of
the JSP scopes via scope attribute - page, request, session, application
- If the variable does not already exist, it gets
created - Variable can be set in 2 different ways
- ltcset var"foo" scope"session" value"..."/gt
- ltcset var"bookId" value"param.Remove"/gt
- ltcset var"foo"gtvalue to be setlt/csetgt
114Example ltcsetgt definition
- ltcset var"customerTable" scope"application"gt
- lttable border"1"gt
- ltcforEach var"customer" items"customers"
gt - lttrgt
- lttdgtcustomer.lastNamelt/tdgt
- lttdgtltcout value"customer.address"
default"no address specified"/gtlt/tdgt - lttdgt
- ltcout value"customer.address"gt
- ltfont color"red"gtno address specifiedlt/fontgt
- lt/coutgt
- lt/tdgt
- lt/trgt
- lt/cforEachgt
- lt/tablegt
- lt/csetgt
115Example ltcsetgt usage
- lth4gtUsing "customerTable" application scope
attribute defined in Set.jsp a first timelt/h4gt - ltcout value"customerTable"
escapeXml"false"/gt - lth4gtUsing "customerTable" application scope
attribute defined in Set.jsp a second timelt/h4gt - ltcout value"customerTable" escapeXml"false"
/gt
116Example ltcsetgt usage
117Variable Support ltcremovegt
- Remove an EL variable
- ltcremove var"cart" scope"session"/gt
118Conditional Tags
- Flow control tags eliminate the need for
scriptlets - Without conditional tags, a page author must
generally resort to using scriptlets - ltcif test..gt
- Conditional execution of its body according to
value of a test attribute - ltcchoosegt
- Performs conditional block execution by the
embedded ltcwhengt and ltcotherwisegt sub tags - if-then-else
119Example ltcif test...gt
- ltcforEach var"customer" items"customers"gt
- ltcif test"customer.address.country
'USA'"gt - customerltbrgt
- lt/cifgt
- lt/cforEachgt
120Example ltcchoosegt, ltcwhengt
- ltcforEach var"customer" items"customers"gt
- ltcchoosegt
- ltcwhen test"customer.address.country
'USA'"gt - ltfont color"blue"gt
- lt/cwhengt
- ltcwhen test"customer.address.country
'Canada'"gt - ltfont color"red"gt
- lt/cwhengt
- ltcotherwisegt
- ltfont color"green"gt
- lt/cotherwisegt
- lt/cchoosegt
- customerlt/fontgtltbrgt
- lt/cforEachgt
121Iterator Tag ltcforEachgt
- Allows you to iterate over a collection of
objects - items represent the collection of objects
- var current item
- varStatus iteration status
- begin, end, step range and interval
- Collection types
- java.util.Collection
- java.util.Map
- value of var attribute should be of type
java.util.Map.Entry
122Example ltcforEachgt
- ltcforEach var"customer" items"customers"gt
- customerltbrgt
- lt/cforEachgt
123Example ltcforEachgt, Range
- ltcforEach var"i" begin"1" end"10"gt
- i
- lt/cforEachgt
124Example ltcforEachgt, Data types
- ltcforEach var"i" items"intArray"gt
- ltcout value"i"/gt
- lt/cforEachgt
- ltcforEach var"string" items"stringArray"gt
- ltcout value"string"/gtltbrgt
- lt/cforEachgt
- ltcforEach var"item" items"enumeration"
begin"2" end"10" step"2"gt - ltcout value"item"/gtltbrgt
- lt/cforEachgt
- ltcforEach var"prop" items"numberMap"
begin"1" end"5"gt - ltcout value"prop.key"/gt ltcout
value"prop.value"/gtltbrgt - lt/cforEachgt
- ltcforEach var"token" items"bleu,blanc,rouge"gt
- ltcout value"token"/gtltbrgtlt/cforEachgt
125(No Transcript)
126Example ltcforEachgt, Iteration status
- ltcforEach var"customer" items"customers"
varStatus"status"gt - lttrgt
- lttdgtltcout value"status.index"/gtlt/tdgt
- lttdgtltcout value"status.count"/gtlt/tdgt
- lttdgtltcout value"status.current.lastName
"/gtlt/tdgt - lttdgtltcout value"status.current.firstName
"/gtlt/tdgt - lttdgtltcout value"status.first"/gtlt/tdgt
- lttdgtltcout value"status.last"/gtlt/tdgt
- lt/trgt...
- lt/cforEachgt
- ltcforEach var"i" begin"100" end"200" step"5"
varStatus"status"gt - ltcif test"status.first"gt
- beginltcout value"status.begin"gtbeginlt/c
outgt - endltcout value"status.end"gtendlt/coutgt
- stepltcout value"status.step"gtsteplt/cou
tgtltbrgt - sequence
- lt/cifgt ...
- lt/cforEachgt
127Example ltcforEachgt, Iteration status
128Example ltcoutgt
- lttable border"1"gt
- ltcforEach var"customer" items"customers"gt
- lttrgt
- lttdgtltcout value"customer.lastName"/gtlt/t
dgt - lttdgtltcout value"customer.phoneHome"
default"no home phone specified"/gtlt/tdgt - lttdgt
- ltcout value"customer.phoneCell"
escapeXml"false"gt - ltfont color"red"gtno cell phone
specifiedlt/fontgt - lt/coutgt
- lt/tdgt
- lt/trgt
- lt/cforEachgt
- lt/tablegt
129Example ltcoutgt
130URL Import ltcimportgt
- More generic way to access URL-based resources
(than ltjspincludegt) - Absolute URL for accessing resources outside of
Web application - Relative URL for accessing resources inside of
the same Web application - More efficient (than ltjspincludegt)
- No buffering
- ltcparamgt tag can be used to specify parameters
(like ltjspparamgt)
131Example ltcimportgt Absolute URL
- ltblockquotegt
- ltexescapeHtmlgt
- ltcimport url"http//www.cnn.com/cnn.rss"/gt
- lt/exescapeHtmlgt
- lt/blockquotegt
132Example ltcurlgt
- lttable border"1" bgcolor"dddddd"gt
- lttrgt
- lttdgt"base", paramABClt/tdgt
- lttdgt
- ltcurl value"base"gt
- ltcparam name"param" value"ABC"/gt
- lt/curlgt
- lt/tdgt
- lt/trgt
- lttrgt
- lttdgt"base", param123lt/tdgt
- lttdgt
- ltcurl value"base"gt
- ltcparam name"param" value"123"/gt
- lt/curlgt
- lt/tdgt
- lt/trgt
- lttrgt
133ltcoutgt
- Evaluates an expression and outputs the result of
the evaluation to the current JspWriter object - Syntax
- ltcout value"value" escapeXml"truefalse"
default"defaultValue" /gt - If escapeXml is true, escape character conversion
134Example ltcoutgt
- lttable border"1"gt
- ltcforEach var"customer" items"customers"gt
- lttrgt
- lttdgtltcout value"customer.lastName"/gtlt/t
dgt - lttdgtltcout value"customer.phoneHome"
default"no home phone specified"/gtlt/tdgt - lttdgt
- ltcout value"customer.phoneCell"
escapeXml"false"gt - ltfont color"red"gtno cell phone
specifiedlt/fontgt - lt/coutgt
- lt/tdgt
- lt/trgt
- lt/cforEachgt
- lt/tablegt
135Database Tags
- All DB actions operate on a DataSource
- Access a DataSource
- Object provided by ltsqldataSourcegt action
- ltsqldataSource var"dataSource"
driver"org.gjt.mm.mysql.Driver"
url"jdbc..."/gtltsqlquery dataSource"dataSour
ce" .../gt
136Example ltsqlsetDataSourcegt
- ltsqlsetDataSource
- var"example"
- driver"com.pointbase.jdbc.jdbcUniversalDriver"
- url"jdbcpointbaseserver//localhost1092/jstl
samplecreatetrue" - /gt
137Example ltsqltransactiongt ltsqlupdategt
- ltsqltransaction dataSource"example"gt
- ltsqlupdate var"newTable"gt
- create table mytable (
- nameid int primary key,
- name varchar(80)
- )
- lt/sqlupdategt
- ltsqlupdate var"updateCount"gt
- INSERT INTO mytable VALUES (1,'Paul
Oakenfold') - lt/sqlupdategt
- ltsqlupdate var"updateCount"gt
- INSERT INTO mytable VALUES (2,'Timo Maas')
- lt/sqlupdategt
- ...
- ltsqlquery var"deejays"gt
- SELECT FROM mytable
138Function Tags
- ltfnlengthgt Length of collection of string
- ltfntoUpperCasegt, ltfntoLowerCasegt Change the
capitalization of a string - ltfnsubstringgt, ltfnsubstringBeforegt,
ltfnsubstringAftergt Get a subset of a string - ltfntrimgt Trim a string
- ltfnreplacegt Replace characters in a string
- ltfnindexOfgt, ltfnstartsWithgt, ltfnendsWith
containsgt, ltfncontainsIgnoreCasegt Check if a
string contains another string - ltfnsplitgt, ltfnjoingt Split a string into an
array,and join a collection into a string - ltfnescapeXmlgt Escape XML characters in the
string
139Example
- lt-- truncate name to 30 chars and display it in
uppercase --gt - fntoUpperCase(fnsubstring(name, 0, 30))
- lt-- Display the text value prior to the first
character --gt - fnsubstringBefore(text, )
- lt-- Scoped variable "name" may contain
whitespaces at the - beginning or end. Trim it first, otherwise we end
up with 's in the URL --gt - ltcurl var"myUrl" value"base/cust/fntrim(n
ame)"/gt - lt-- Display the name if it contains the search
string --gt - ltcif test"fncontainsIgnoreCase(name,
searchString)"gt - Found name name
- lt/cifgt
- lt-- Display text value with bullets instead of
- --gt - fnreplace(text, -, 149)
140I18N and Formatting Tags
- Setting locale
- ltfmtsetLocalegt Override client-specified locale
for a page - ltfmtrequestEncodinggt -Set the request's
character encoding, in order to be able to
correctly decode request parameter values whose
encoding is different from ISO-8859-1
141I18N and Formatting Tags
- MessagingTags
- ltfmtbundlegt-specify a resource bundle for a page
- ltfmtmessage keygt
- used to output localized strings
- ltfmtparamgt subtag provides a single argument
(for parametric replacement) to the compound
message or pattern in its parent message tag
142I18N and Formatting Tags
- Number and Date formatting
- ltfmtformatNumbergt, ltfmtparseNumbergt
- ltfmtformatDategt, ltfmtparseDategt
- ltfmtsetTimeZonegt, ltfmttimeZone gt
143Example
- ltfmtsetLocale value"de"/gt
- ltfmtbundle basename"org.apache.taglibs.standard.
examples.i18n.Resources"gt - ltfmtmessagegt
- greetingMorning
- lt/fmtmessagegt
- lt/fmtbundlegt
144Example ltfmtsetLocalegt
145Example
- ltjspuseBean id"now" class"java.util.Date" /gt
- ltfmtsetLocale value"en-US" /gt
- ltulgt
- ltligt Formatting current date as "GMT"ltbrgt
- ltfmttimeZone value"GMT"gt
- ltfmtformatDate value"now"
dateStyle"full" timeStyle"full"/gt - lt/fmttimeZonegt
- ltligt Formatting current date as "GMT100", and
parsing - its date and time componentsltbrgt
- ltfmttimeZone value"GMT100"gt
- ltfmtformatDate value"now" type"both"
dateStyle"full" - timeStyle"full"
var"formatted"/gt - ltfmtparseDate value"formatted"
type"both" dateStyle"full" - timeStyle"full" timeZone"PST"
var"parsedDateTime"/gt - Parsed date ltfmtformatDate
value"parsedDateTime" type"date" -
dateStyle"full"/gtltbrgt - Parsed time ltfmtformatDate
value"parsedDateTime" type"time"
146Example using browser locale en-us