JSP 1.2 Custom Tags

115
1 JSP 1.2 JSP 1.2 Custom Tags Custom Tags

Transcript of JSP 1.2 Custom Tags

Page 1: JSP 1.2 Custom Tags

1

JSP 1.2JSP 1.2Custom TagsCustom Tags

Page 2: JSP 1.2 Custom Tags

2

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

Stephanie Bodoff of Sun Microsystems– Many slides are borrowed from “Sevlet/JSP” codecamp

material authored by Doris Chen of Sun Microsystems

Page 3: JSP 1.2 Custom Tags

3

Revision History● 10/13/2003: version 1: created by Sang Shin● Things to do– speaker notes need to be added and polished– some concepts need to be explained better – advanced usage scenarios (tag variables, listener,

etc in JSP 1.2) still need to be discussed– “how does it work” part needs to be polished up a bit

Page 4: JSP 1.2 Custom Tags

4

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?

Page 5: JSP 1.2 Custom Tags

5

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

Page 6: JSP 1.2 Custom Tags

6

Evolution ofEvolution ofWeb tier technologyWeb tier technology

Page 7: JSP 1.2 Custom Tags

7

Web Application Designs

Page 8: JSP 1.2 Custom Tags

8

Where does custom tags fit in?

Page 9: JSP 1.2 Custom Tags

9

Standard Action Tags (or Tags) ● <jsp:useBean>– Instantiate JavaBean object

● <jsp:getProperty>– Allow accessing bean properties

● <jsp:setProperty>– Allow setting bean properties

Page 10: JSP 1.2 Custom Tags

10

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

Page 11: JSP 1.2 Custom Tags

11

What is a What is a Custom Tag?Custom Tag?

Page 12: JSP 1.2 Custom Tags

12

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

Page 13: JSP 1.2 Custom Tags

13

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

Page 14: JSP 1.2 Custom Tags

14

Custom Tag Examples● Getting/setting Implicit objects● Processing forms● Accessing database● Flow control● Iterations ● Many more

Page 15: JSP 1.2 Custom Tags

15

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

Page 16: JSP 1.2 Custom Tags

16

Why Custom Tags?Why Custom Tags?

Page 17: JSP 1.2 Custom Tags

17

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

Page 18: JSP 1.2 Custom Tags

18

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

source: more Servlets and JSP[2]

Page 19: JSP 1.2 Custom Tags

19

Quick Introduction onQuick Introduction onComponents that make up Components that make up Custom tag architecture Custom tag architecture

(in JSP 1.2)(in JSP 1.2)

Page 20: JSP 1.2 Custom Tags

20

Three things make up custom tagarchitecture● 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

Page 21: JSP 1.2 Custom Tags

21

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

Page 22: JSP 1.2 Custom Tags

22

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>

Page 23: JSP 1.2 Custom Tags

23

Example: Tag Handler (page 1)ExampleTag.javapackage 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. * <P> * 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. */

Page 24: JSP 1.2 Custom Tags

24

Example: Tag Handler (page 2)ExampleTag.javapublic 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); }}

Page 25: JSP 1.2 Custom Tags

25

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

Page 26: JSP 1.2 Custom Tags

26

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">

<!-- a tag library descriptor -->

<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>

Page 27: JSP 1.2 Custom Tags

27

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>

Page 28: JSP 1.2 Custom Tags

28

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)

Page 29: JSP 1.2 Custom Tags

29

JSP page● Declare the tag library via taglib directive ● Use tags using custom tag syntax

Page 30: JSP 1.2 Custom Tags

30

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

Page 31: JSP 1.2 Custom Tags

31

Custom Tag Syntax in a JSP page<prefix:tag attr1="value" ... attrN="value" /> or <prefix:tag attr1="value" ... attrN="value" > body</prefix:tag>

prefix: distinguishes tag librarytag: identifies a tag (within the tag library)attr1 ... attrN: modify the behavior of the tag

Page 32: JSP 1.2 Custom Tags

32

Example: JSP page SimpleExample.jsp<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><!-- Illustration of very simple JSP custom tag.

Taken from More Servlets and JavaServer Pagesfrom Prentice Hall and Sun Microsystems Press,http://www.moreservlets.com/.(C) 2002 Marty Hall; may be freely used or adapted.--><HTML><HEAD><%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %><TITLE><msajsp:example /></TITLE><LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"></HEAD><BODY><H1><msajsp:example /></H1><msajsp:example /></BODY></HTML>

Page 33: JSP 1.2 Custom Tags

33

Example: Accessing SimpleExample.jsp

Page 34: JSP 1.2 Custom Tags

34

How to build, configure How to build, configure and deploy tag library and deploy tag library

Page 35: JSP 1.2 Custom Tags

35

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– build.xml (ant build file)– src (dir where *.java files with proper package

structure reside)– web (dir)

● WEB-INF (dir)● *.tld● tags (dir - needed for JSP 2.0 tag files)

● *.jsp

Page 36: JSP 1.2 Custom Tags

36

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– build (unpacked *.war file)– dist (packed *.war file)

Page 37: JSP 1.2 Custom Tags

37

Usage Scenarios Usage Scenarios of Custom Tagsof Custom Tags

(in JSP 1.2) (in JSP 1.2)

Page 38: JSP 1.2 Custom Tags

38

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

Page 39: JSP 1.2 Custom Tags

39

Usage Scenarios of Custom Tags

● Bundling listeners with tag libraries● Checking syntax with TagLibraryValidator● Handling Exceptions with TryCatchFinally

interface● Looping without generating BodyContent

Page 40: JSP 1.2 Custom Tags

40

Defining a basic tagDefining a basic tag(We already saw(We already saw

an example.)an example.)

Page 41: JSP 1.2 Custom Tags

41

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

Page 42: JSP 1.2 Custom Tags

42

Assigning attributes Assigning attributes to tagsto tags

Page 43: JSP 1.2 Custom Tags

43

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

Page 44: JSP 1.2 Custom Tags

44

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

public void setX(String value1){ doSomethingWith(value1);}

Page 45: JSP 1.2 Custom Tags

45

Example: 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.) * <P> * 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. */

Page 46: JSP 1.2 Custom Tags

46

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); }}

Page 47: JSP 1.2 Custom Tags

47

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. * <P> * 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. */

Page 48: JSP 1.2 Custom Tags

48

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; }}

Page 49: JSP 1.2 Custom Tags

49

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)

Page 50: JSP 1.2 Custom Tags

50

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

Page 51: JSP 1.2 Custom Tags

51

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">

<!-- a tag library descriptor -->

<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>

Page 52: JSP 1.2 Custom Tags

52

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>

Page 53: JSP 1.2 Custom Tags

53

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>

Page 54: JSP 1.2 Custom Tags

54

Example: Accessing PrimeExample.jsp

Page 55: JSP 1.2 Custom Tags

55

Including Tag BodyIncluding Tag Body

Page 56: JSP 1.2 Custom Tags

56

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

Page 57: JSP 1.2 Custom Tags

57

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

Page 58: JSP 1.2 Custom Tags

58

Example: 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. * <P> * 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. */

Page 59: JSP 1.2 Custom Tags

59

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; }

...

Page 60: JSP 1.2 Custom Tags

60

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 }

Page 61: JSP 1.2 Custom Tags

61

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 }}

Page 62: JSP 1.2 Custom Tags

62

TLD● The bodycontent element should contain the

value JSP– <bodycontent>JSP</bodycontent>

Page 63: JSP 1.2 Custom Tags

63

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> ...

Page 64: JSP 1.2 Custom Tags

64

Example: JSP Page (HeadingExample.jsp)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><!-- Illustration of HeadingTag tag.

Taken from More Servlets and JavaServer Pagesfrom Prentice Hall and Sun Microsystems Press,http://www.moreservlets.com/.(C) 2002 Marty Hall; may be freely used or adapted.--><HTML><HEAD><TITLE>Some Tag-Generated Headings</TITLE></HEAD><BODY><%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %><msajsp:heading bgColor="#C0C0C0">Default Heading</msajsp:heading><P><msajsp:heading bgColor="BLACK" color="WHITE">White on Black Heading</msajsp:heading>

Page 65: JSP 1.2 Custom Tags

65

Example: JSP Page (HeadingExample.jsp)

<P><msajsp:heading bgColor="#EF8429" fontSize="60" border="5">Large Bordered Heading</msajsp:heading><P><msajsp:heading bgColor="CYAN" width="100%">Heading with Full-Width Background</msajsp:heading><P><msajsp:heading bgColor="CYAN" fontSize="60" fontList="Brush Script MT, Times, serif">Heading with Non-Standard Font</msajsp:heading></BODY></HTML>

Page 66: JSP 1.2 Custom Tags

66

Page 67: JSP 1.2 Custom Tags

67

OptionallyOptionallyIncluding Tag BodyIncluding Tag Body

Page 68: JSP 1.2 Custom Tags

68

Optionally Including Tag body● Decision of usage of body content is decided

at request time● Body content is not modified

Page 69: JSP 1.2 Custom Tags

69

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

Page 70: JSP 1.2 Custom Tags

70

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. * <P> * 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. */

Page 71: JSP 1.2 Custom Tags

71

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); } }}

Page 72: JSP 1.2 Custom Tags

72

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>

...

Page 73: JSP 1.2 Custom Tags

73

Example: JSP Page (DebugExample.jsp)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><!-- Illustration of DebugTag tag.

Taken from More Servlets and JavaServer Pagesfrom Prentice Hall and Sun Microsystems Press,http://www.moreservlets.com/.(C) 2002 Marty Hall; may be freely used or adapted.--><HTML><HEAD><TITLE>Using the Debug Tag</TITLE><LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"></HEAD><BODY><H1>Using the Debug Tag</H1><%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.<P>

Page 74: JSP 1.2 Custom Tags

74

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>

Page 75: JSP 1.2 Custom Tags

75

DebugTag without “debug” inputparameter

Page 76: JSP 1.2 Custom Tags

76

Accessing DebugExample.jsp with “debug=true” input param

Page 77: JSP 1.2 Custom Tags

77

Manipulating Tag BodyManipulating Tag Body

Page 78: JSP 1.2 Custom Tags

78

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

Page 79: JSP 1.2 Custom Tags

79

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

Page 80: JSP 1.2 Custom Tags

80

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 (&lt;, &gt;, &quot;, and &amp;). * 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/. * &copy; 2002 Marty Hall; may be freely used or adapted. */

Page 81: JSP 1.2 Custom Tags

81

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); }}

Page 82: JSP 1.2 Custom Tags

82

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>

...

Page 83: JSP 1.2 Custom Tags

83

Example: JSP Page (FilterExample.jsp)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><!-- Illustration of FilterTag tag.

Taken from More Servlets and JavaServer Pagesfrom Prentice Hall and Sun Microsystems Press,http://www.moreservlets.com/.(C) 2002 Marty Hall; may be freely used or adapted.--><HTML><HEAD><TITLE>HTML Logical Character Styles</TITLE><LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"></HEAD><BODY><H1>HTML Logical Character Styles</H1>Physical character styles (B, I, etc.) are rendered consistentlyin 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:<P>

Page 84: JSP 1.2 Custom Tags

84

Example: JSP Page (FilterExample.jsp)<%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %><TABLE BORDER=1 ALIGN="CENTER"><TR CLASS="COLORED"><TH>Example<TH>Result<TR><TD><PRE><msajsp:filter><EM>Some emphasized text.</EM><BR><STRONG>Some strongly emphasized text.</STRONG><BR><CODE>Some code.</CODE><BR><SAMP>Some sample text.</SAMP><BR><KBD>Some keyboard text.</KBD><BR><DFN>A term being defined.</DFN><BR><VAR>A variable.</VAR><BR><CITE>A citation or reference.</CITE></msajsp:filter></PRE><TD><EM>Some emphasized text.</EM><BR><STRONG>Some strongly emphasized text.</STRONG><BR><CODE>Some code.</CODE><BR><SAMP>Some sample text.</SAMP><BR><KBD>Some keyboard text.</KBD><BR><DFN>A term being defined.</DFN><BR><VAR>A variable.</VAR><BR><CITE>A citation or reference.</CITE></TABLE></BODY></HTML>

Page 85: JSP 1.2 Custom Tags

85

To be added

Page 86: JSP 1.2 Custom Tags

86

Including or Manipulating Including or Manipulating Tag Body Multiple TimesTag Body Multiple Times

Page 87: JSP 1.2 Custom Tags

87

Tag handler class● Tag handler class should extend

BodyTagSupport class ● doAfterBody() now returns

EVAL_BODY_TAG (EVAL_BODY_AGAIN in JSP 1.2)

Page 88: JSP 1.2 Custom Tags

88

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. * <P> * 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. */

Page 89: JSP 1.2 Custom Tags

89

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; } }

Page 90: JSP 1.2 Custom Tags

90

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); } }

Page 91: JSP 1.2 Custom Tags

91

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> ...

Page 92: JSP 1.2 Custom Tags

92

Example: JSP Page (RepeatExample.jsp)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><!-- Illustration of RepeatTag tag.

Taken from More Servlets and JavaServer Pagesfrom Prentice Hall and Sun Microsystems Press,http://www.moreservlets.com/.(C) 2002 Marty Hall; may be freely used or adapted. --><HTML><HEAD><TITLE>Some 40-Digit Primes</TITLE><LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"></HEAD><BODY><H1>Some 40-Digit Primes</H1>Each entry in the following list is the first prime number higher than a randomly selected 40-digit number.

Page 93: JSP 1.2 Custom Tags

93

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>

Page 94: JSP 1.2 Custom Tags

94

To be added

Page 95: JSP 1.2 Custom Tags

95

More detailed informationMore detailed informationon How to declare tagon How to declare tag

library using taglib directivelibrary using taglib directive

Page 96: JSP 1.2 Custom Tags

96

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>

Page 97: JSP 1.2 Custom Tags

97

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"%>

Page 98: JSP 1.2 Custom Tags

98

More detailed information onMore detailed information onHow to Configure tag library How to Configure tag library

with Web applicationwith Web application

Page 99: JSP 1.2 Custom Tags

99

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

Page 100: JSP 1.2 Custom Tags

100

How does it Work?How does it Work?

Page 101: JSP 1.2 Custom Tags

101

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

Page 102: JSP 1.2 Custom Tags

102

Sequence of Calls from Container

Page 103: JSP 1.2 Custom Tags

103

TagSupport Implements Tag Interface

Page 104: JSP 1.2 Custom Tags

104

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

Page 105: JSP 1.2 Custom Tags

105

Calling Sequence from the ContainerObtainhandlerObtainhandler

Set propertiesSet properties Set attributevalues

Set attributevalues

Release( )Release( )

doStartTag( )

Process bodyProcess body

doEndTag( )

Release( )Release( )

ContinueContinueStop

Skip_page Eval_page

Skip_body

Eval_body_include

setPageContext( )setParent( )

Page 106: JSP 1.2 Custom Tags

106

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

Page 107: JSP 1.2 Custom Tags

107

How Is a Tag Invoked?

<prefix:actionName attr1=“value1” attr2=“value2”>

The body

</prefix:actionName>

• setAttr1(“values1”)

• setAttr2(“value2”)

• doStartTag( )

• setBodyContent( )

• doInitBody( )

• doAfterBody( )

• doEndTag( )

setPageContext()setParent()

Page 108: JSP 1.2 Custom Tags

108

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.

Page 109: JSP 1.2 Custom Tags

109

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

Page 110: JSP 1.2 Custom Tags

110

How Does BodyTag Work?

Page 111: JSP 1.2 Custom Tags

111

BodyContent

Page 112: JSP 1.2 Custom Tags

112

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

Page 113: JSP 1.2 Custom Tags

113

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().

Page 114: JSP 1.2 Custom Tags

114

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

Page 115: JSP 1.2 Custom Tags

115

Passion!Passion!