This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA
* 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. */
23
Example: 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); } }
24
Tag Library Descriptor (TLD) ●
XML file that describes – – – –
●
●
Container knows which tag is associated with which tag handler class via this file Located –
●
tag name bodycontent attributes tag handler class
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
Example: TLD (page 2) msajsp-tags.tld
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: distinguishes tag library tag: identifies a tag (within the tag library) attr1 ... attrN: modify the behavior of the tag 31
Example: JSP page SimpleExample.jsp
* 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. */ 45
Example: 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.random(len)); out.print(prime); } catch(IOException ioe) { System.out.println("Error generating prime: " + ioe); } return(SKIP_BODY); } }
46
Example: 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. *
* 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. */
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; } } /** Servers are permitted to reuse tag instances * once a request is finished. So, this resets * the len field. */ public void release() { len = 50; } }
48
TLD ●
●
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) 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)
51
Example: TLD (page 2) ...
52
Example: JSP Page (PrimeExample.jsp)
* 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. */
58
Example: 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 width=null; public void setBgColor(String bgColor) { this.bgColor = bgColor; } public void setColor(String color) { this.color = color; } ...
59
Example: Tag Handler (page 3) HeadingTag.java public int doStartTag() { try { JspWriter out = pageContext.getOut(); out.print("
"); 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(" |
---|
<msajsp:heading bgColor="BLACK" color="WHITE"> White on Black Heading 64
Example: JSP Page (HeadingExample.jsp)
<msajsp:heading bgColor="#EF8429" fontSize="60" border="5"> Large Bordered Heading
<msajsp:heading bgColor="CYAN" width="100%"> Heading with Full-Width Background
<msajsp:heading bgColor="CYAN" fontSize="60" fontList="Brush Script MT, Times, serif"> Heading with Non-Standard Font
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.*; /** A tag that includes the body content only if * the "debug" request parameter is set. *
* 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. */ 73 Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda. * 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 * 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. */
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
72
Example: JSP Page (DebugExample.jsp) <TITLE>Using the Debug Tag Using the Debug Tag
<%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %> Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.
Example: JSP Page (DebugExample.jsp) <msajsp:debug> Debug:
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. *
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
82
Example: JSP Page (FilterExample.jsp) <TITLE>HTML Logical Character Styles HTML Logical Character Styles
Physical character styles (B, I, etc.) are rendered consistently in different browsers. Logical character styles, however, may be rendered differently by different browsers. Here's how your browser (<%= request.getHeader("User-Agent") %>) renders the HTML 4.0 logical character styles:
83
Example: JSP Page (FilterExample.jsp) <%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>
Example Result <msajsp:filter> <EM>Some emphasized text.
<STRONG>Some strongly emphasized text.
Some code.
<SAMP>Some sample text.
Some keyboard text.
A term being defined.
A variable.
A citation or reference. <EM>Some emphasized text.
<STRONG>Some strongly emphasized text.
Some code.
<SAMP>Some sample text.
Some keyboard text.
A term being defined.
A variable.
A citation or reference.
84
To be added
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.*; /** A tag that repeats the body the specified * number of times. *
88
Example: 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; } }
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
91
Example: JSP Page (RepeatExample.jsp) <TITLE>Some 40-Digit Primes Some 40-Digit Primes
Each entry in the following list is the first prime number higher than a randomly selected 40-digit number.
92
Example: JSP Page (RepeatExample.jsp) <%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %> <msajsp:repeat reps='<%= request.getParameter("repeats") %>'>
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>
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 handler handler
Set Setproperties properties setPageContext( ) setParent( )
doStartTag( )
Set Setattribute attribute values values
Eval_body_include Process Processbody body
Skip_body Skip_page
doEndTag( )
Eval_page
Release( Release())
Release( Release() )
Stop
Continue Continue
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()
<prefix:actionName attr1=“value1” attr2=“value2” > The body
•
setAttr1(“values1”)
•
setAttr2(“value2”)
•
doStartTag( )
•
setBodyContent( )
•
doInitBody( )
•
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