1 jsp 1.2 custom tags. 2 agenda ● what is and why custom tags? ● components that make up custom...

146
1 JSP 1.2 Custom Tags

Upload: samson-hicks

Post on 28-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

1

JSP 1.2Custom Tags

Page 2: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

2

Agenda

● What is and why custom tags?● Components that make up custom tag

architecture● How to create custom tags?● How does it work?● JSTL

Page 3: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

3

Evolution of

Web tier technology

Page 4: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

4

Web Application Designs

Page 5: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

5

Standard Action Tags ● <jsp:useBean>

– Instantiate Java Bean class without explicit Java programming language

● <jsp:getProperty>– Allow accessing bean properties

● <jsp:setProperty>– Allow setting bean properties

Page 6: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

6

Standard Action Tags● <jsp:forward>

– Forwards request to HTML page, JSP, or servlet● <jsp:include>

– Includes data in a JSP page from another file● <jsp:plugin>

– Downloads Java plugin to browser to execute applet or bean

Page 7: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

7

What is Custom Tag?

Page 8: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

8

What is a Custom Tag?● User defined JSP language elements● Encapsulates recurring tasks● Distributed in a “custom made” tag library

Page 9: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

9

Custom 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

Page 10: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

10

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

Page 11: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

11

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 12: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

12

Why Custom Tags?

Page 13: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

13

Why 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

Page 14: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

14

Custom 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

source: more ervlets and JSP[2]

Page 15: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

15

Quick Introduction onComponents that make up Custom tag architecture

Page 16: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

16

Three 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

Page 17: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

17

Steps for implementing custom tags ● Write tag handlers

● Write Tag library descriptor (TLD) file

● Write JSP pages that use tags

Page 18: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

18

Tag 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/<package-directory-structure>

Page 19: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

19

Example: 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. * <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 20: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

20

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 21: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

21

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

● Location specified in JSP file– Via uri attribute of taglib directive

Page 22: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

22

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 23: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

23

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 24: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

24

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

Page 25: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

25

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 26: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

26

Custom Tag Syntax in JSP page

<prefix:tag attr1="value" ... attrN="value" />

or

<prefix:tag attr1="value" ... attrN="value" >

body

</prefix:tag>

prefix: distinguishes tag library

tag: identifies a tag (within the tag library)

attr1 ... attrN: modify the behavior of the tag

Page 27: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

27

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 28: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

28

Example: Accessing SimpleExample.jsp

Page 29: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

29

Sample codes we will

use in this class

Page 30: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

30

Usage Scenarios of Custom Tags

Page 31: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

31

Usage 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

Page 32: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

32

Defining a basic tag

Page 33: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

33

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 34: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

34

Assigning attributes to tags

Page 35: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

35

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 36: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

36

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 37: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

37

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 38: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

38

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 39: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

39

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 40: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

40

Example: Tag Handler (page 4) PrimeTag.javapublic 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 41: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

41

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 42: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

42

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 43: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

43

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 44: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

44

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 45: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

45

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 46: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

46

Example: Accessing PrimeExample.jsp

Page 47: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

47

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 48: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

48

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 49: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

49

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 50: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

50

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 51: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

51

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 52: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

52

TLD

● The bodycontent element should contain the value JSP– <bodycontent>JSP</bodycontent>

Page 53: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

53

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 54: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

54

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 55: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

55

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 56: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

56

Page 57: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

57

OptionallyIncluding Tag Body

Page 58: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

58

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

at request time● Body content is not modified

Page 59: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

59

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 60: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

60

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 61: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

61

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 62: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

62

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 63: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

63

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 64: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

64

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 65: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

65

DebugTag without “debug” inputparameter

Page 66: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

66

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

Page 67: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

67

Manipulating Tag Body

Page 68: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

68

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 69: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

69

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 70: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

70

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 71: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

71

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 72: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

72

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 73: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

73

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 74: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

74

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 75: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

75

To be added

Page 76: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

76

Including or Manipulating Tag Body Multiple Times

Page 77: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

77

Tag handler class

● Tag handler class should extend BodyTagSupport class

● doAfterBody() now returns EVAL_BODY_TAG (EVAL_BODY_AGAIN in JSP 1.2)

Page 78: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

78

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 79: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

79

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 80: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

80

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 81: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

81

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 82: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

82

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 83: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

83

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 84: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

84

To be added

Page 85: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

85

More detailed informationon How to declare tag

library using taglib directive

Page 86: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

86

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 87: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

87

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 88: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

88

More detailed information on

How to Configure tag library

with Web application

Page 89: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

89

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 90: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

90

Configuring tag library globally(for all Web apps on a server) ● For Tomcat of Java WSDP

– Cove *.jar file (tag library) to <JWSDP_HOME>/common/lib

– Any jar files under <JWSDP_HOME>/common/lib will be available to all Web apps

Page 91: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

91

How does it Work?

Page 92: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

92

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 93: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

93

Sequence of Calls from Container

Page 94: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

94

TagSupport Implements Tag Interface

Page 95: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

95

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 96: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

96

Calling Sequence from the Container

Obtainhandler

Obtainhandler

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 97: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

97

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 98: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

98

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 99: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

99

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.

Page 100: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

100

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 101: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

101

How Does BodyTag Work?

Page 102: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

102

BodyContent

Page 103: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

103

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 104: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

104

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 105: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

105

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 106: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

106

What is JSTL?

● Standard set of tag libraries● Encapsulates core functionality common to

many JSP applications– iteration, conditionals, XML, database access,

internationalized formatting

Page 107: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

107

Why 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

Page 108: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

108

JSTL 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

Page 109: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

109

Declaration of JSTL Tag Libraries

● Core – <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

● XML – <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

● Internationalization (i18n) – <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

● Database (SQL)– <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

● Functions – <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Page 110: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

110

JSTL Tag Library Jar Files● Distributed as two jar files

– standard.jar– jstl.jar

● Under JWSDP– <jwsdp-install>/jstl/lib/standard.jar– <jwsdp-install>/jstl/lib/jstl.jar

● How to configure them with your Web apps– Load them automatically with every Web app

● copy them to <jwsdp-install>/common/lib

– Load them only with your app● copy them to <your-app-root>/WEB-INF/lib

Page 111: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

111

Core Tags Types (page 1)● Variable support

– <c:set>– <c:remove>

● Conditional– <c:if>– <c:choose>

● <c:when>● <c:otherwise>

● Iteration– <c:forEach>– <c:forTokens>

Page 112: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

112

Core Tags Types (page 2)● URL management

– <c:import>● <c:param>

– <c:redirect>● <c:param>

– <c:url>● <c:param>

● General purpose– <c:out>– <c:catch>

Page 113: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

113

Variable Support, <c:set>

● 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– <c:set var="foo" scope="session" value="..."/>

● <c:set var="bookId" value="${param.Remove}"/>

– <c:set var="foo">value to be set</c:set>

Page 114: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

114

Example: <c:set> definition

<c:set var="customerTable" scope="application"><table border="1"> <c:forEach var="customer" items="${customers}"> <tr> <td>${customer.lastName}</td> <td><c:out value="${customer.address}" default="no address specified"/></td> <td> <c:out value="${customer.address}"> <font color="red">no address specified</font></c:out> </td></tr> </c:forEach></table></c:set>

Page 115: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

115

Example: <c:set> usage

<h4>Using "customerTable" application scope attribute defined in Set.jsp a first time</h4>

<c:out value="${customerTable}" escapeXml="false"/>

<h4>Using "customerTable" application scope attribute defined in Set.jsp a second time</h4>

<c:out value="${customerTable}" escapeXml="false" />

Page 116: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

116

Example: <c:set> usage

Page 117: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

117

Variable Support <c:remove>

● Remove an EL variable– <c:remove var="cart" scope="session"/>

Page 118: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

118

Conditional Tags● Flow control tags eliminate the need for

scriptlets– Without conditional tags, a page author must

generally resort to using scriptlets● <c:if test=”..”>

– Conditional execution of its body according to value of a test attribute

● <c:choose>– Performs conditional block execution by the

embedded <c:when> and <c:otherwise> sub tags– if-then-else

Page 119: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

119

Example: <c:if test=”...”>

<c:forEach var="customer" items="${customers}"> <c:if test="${customer.address.country == 'USA'}"> ${customer}<br> </c:if></c:forEach>

Page 120: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

120

Example: <c:choose>, <c:when>

<c:forEach var="customer" items="${customers}"> <c:choose> <c:when test="${customer.address.country == 'USA'}"> <font color="blue"> </c:when> <c:when test="${customer.address.country == 'Canada'}"> <font color="red"> </c:when> <c:otherwise> <font color="green"> </c:otherwise> </c:choose> ${customer}</font><br></c:forEach>

Page 121: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

121

Iterator Tag: <c:forEach>

● 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

Page 122: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

122

Example: <c:forEach>

<c:forEach var="customer" items="${customers}"> ${customer}<br></c:forEach>

Page 123: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

123

Example: <c:forEach>, Range

<c:forEach var="i" begin="1" end="10"> ${i} •</c:forEach>

Page 124: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

124

Example: <c:forEach>, Data types<c:forEach var="i" items="${intArray}"> <c:out value="${i}"/> •</c:forEach>

<c:forEach var="string" items="${stringArray}"> <c:out value="${string}"/><br></c:forEach>

<c:forEach var="item" items="${enumeration}" begin="2" end="10" step="2"> <c:out value="${item}"/><br></c:forEach>

<c:forEach var="prop" items="${numberMap}" begin="1" end="5"> <c:out value="${prop.key}"/> = <c:out value="${prop.value}"/><br></c:forEach>

<c:forEach var="token" items="bleu,blanc,rouge"> <c:out value="${token}"/><br></c:forEach>

Page 125: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

125

Page 126: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

126

Example: <c:forEach>, Iteration status<c:forEach var="customer" items="${customers}" varStatus="status"> <tr> <td><c:out value="${status.index}"/></td> <td><c:out value="${status.count}"/></td> <td><c:out value="${status.current.lastName}"/></td> <td><c:out value="${status.current.firstName}"/></td> <td><c:out value="${status.first}"/></td> <td><c:out value="${status.last}"/></td> </tr>...</c:forEach><c:forEach var="i" begin="100" end="200" step="5" varStatus="status"> <c:if test="${status.first}"> begin:<c:out value="${status.begin}">begin</c:out> end:<c:out value="${status.end}">end</c:out> step:<c:out value="${status.step}">step</c:out><br> sequence: </c:if> ...</c:forEach>

Page 127: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

127

Example: <c:forEach>, Iteration status

Page 128: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

128

Example: <c:out><table border="1"> <c:forEach var="customer" items="${customers}"> <tr> <td><c:out value="${customer.lastName}"/></td> <td><c:out value="${customer.phoneHome}" default="no home phone

specified"/></td> <td> <c:out value="${customer.phoneCell}" escapeXml="false"> <font color="red">no cell phone specified</font> </c:out> </td> </tr> </c:forEach></table>

Page 129: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

129

Example: <c:out>

Page 130: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

130

URL Import: <c:import>

● More generic way to access URL-based resources (than <jsp:include>)– Absolute URL: for accessing resources outside of

Web application– Relative URL: for accessing resources inside of

the same Web application

● More efficient (than <jsp:include>)– No buffering

● <c:param> tag can be used to specify parameters (like <jsp:param>)

Page 131: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

131

Example: <c:import> Absolute URL

<blockquote><ex:escapeHtml> <c:import url="http://www.cnn.com/cnn.rss"/></ex:escapeHtml></blockquote>

Page 132: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

132

Example: <c:url> <table border="1" bgcolor="#dddddd"> <tr> <td>"base", param=ABC</td> <td>

<c:url value="base"> <c:param name="param" value="ABC"/> </c:url> </td> </tr> <tr> <td>"base", param=123</td> <td> <c:url value="base"> <c:param name="param" value="123"/> </c:url> </td> </tr> <tr>

Page 133: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

133

<c:out>● Evaluates an expression and outputs the

result of the evaluation to the current JspWriter object

● Syntax– <c:out value="value" [escapeXml="{true|false}"]

[default="defaultValue"] />– If escapeXml is true, escape character conversion

Page 134: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

134

Example: <c:out> <table border="1"> <c:forEach var="customer" items="${customers}"> <tr> <td><c:out value="${customer.lastName}"/></td> <td><c:out value="${customer.phoneHome}" default="no home phone

specified"/></td> <td> <c:out value="${customer.phoneCell}" escapeXml="false"> <font color="red">no cell phone specified</font> </c:out> </td> </tr> </c:forEach></table>

Page 135: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

135

Database Tags

● All DB actions operate on a DataSource● Access a DataSource

– Object provided by <sql:dataSource> action

<sql:dataSource var="dataSource" driver="org.gjt.mm.mysql.Driver" url="jdbc:..."/><sql:query dataSource="${dataSource}" .../>

Page 136: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

136

Example: <sql:setDataSource>

<sql:setDataSource

var="example"

driver="com.pointbase.jdbc.jdbcUniversalDriver"

url="jdbc:pointbase:server://localhost:1092/jstlsample;create=true"

/>

Page 137: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

137

Example: <sql:transaction> & <sql:update> <sql:transaction dataSource="${example}">

<sql:update var="newTable"> create table mytable ( nameid int primary key, name varchar(80) ) </sql:update>

<sql:update var="updateCount"> INSERT INTO mytable VALUES (1,'Paul Oakenfold') </sql:update> <sql:update var="updateCount"> INSERT INTO mytable VALUES (2,'Timo Maas') </sql:update> ...

<sql:query var="deejays"> SELECT * FROM mytable </sql:query>

</sql:transaction>

Page 138: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

138

Function Tags● <fn:length> Length of collection of string ● <fn:toUpperCase>, <fn:toLowerCase> Change the capitalization of a string ● <fn:substring>, <fn:substringBefore>, <fn:substringAfter> Get a subset of a

string ● <fn:trim> Trim a string ● <fn:replace> Replace characters in a string ● <fn:indexOf>, <fn:startsWith>, <fn:endsWith contains>,

<fn:containsIgnoreCase> Check if a string contains another string ● <fn:split>, <fn:join> Split a string into an array,and join a collection into a string ● <fn:escapeXml> Escape XML characters in the string

Page 139: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

139

Example: ●<%-- truncate name to 30 chars and display it in uppercase --%>

●${fn:toUpperCase(fn:substring(name, 0, 30))}

●<%-- Display the text value prior to the first ’*’ character --%>

●${fn:substringBefore(text, ’*’)}

●<%-- Scoped variable "name" may contain whitespaces at the

●beginning or end. Trim it first, otherwise we end up with +'s in the URL --%>

●<c:url var="myUrl" value="${base}/cust/${fn:trim(name)}"/>

●<%-- Display the name if it contains the search string --%>

●<c:if test="${fn:containsIgnoreCase(name, searchString)}">

● Found name: ${name}

●</c:if>

●<%-- Display text value with bullets instead of ’-’ --%>

●${fn:replace(text, ’-’, ’&#149;’)}

Page 140: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

140

I18N and Formatting Tags ● Setting locale

– <fmt:setLocale> :Override client-specified locale for a page

– <fmt:requestEncoding> -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

Page 141: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

141

I18N and Formatting Tags ● MessagingTags

– <fmt:bundle>-specify a resource bundle for a page– <fmt:message key=””>

● used to output localized strings● <fmt:param> subtag provides a single argument

(for parametric replacement) to the compound message or pattern in its parent message tag

Page 142: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

142

I18N and Formatting Tags

● Number and Date formatting– <fmt:formatNumber>, <fmt:parseNumber>– <fmt:formatDate>, <fmt:parseDate>– <fmt:setTimeZone>, <fmt:timeZone >

Page 143: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

143

Example:

<fmt:setLocale value="de"/>

<fmt:bundle basename="org.apache.taglibs.standard.examples.i18n.Resources">

<fmt:message>

greetingMorning

</fmt:message>

</fmt:bundle>

Page 144: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

144

Example: <fmt:setLocale>

Page 145: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

145

Example: <jsp:useBean id="now" class="java.util.Date" /><fmt:setLocale value="en-US" />

<ul> <li> Formatting current date as "GMT":<br> <fmt:timeZone value="GMT"> <fmt:formatDate value="${now}" dateStyle="full" timeStyle="full"/> </fmt:timeZone>

<li> Formatting current date as "GMT+1:00", and parsing its date and time components:<br> <fmt:timeZone value="GMT+1:00"> <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full" var="formatted"/> <fmt:parseDate value="${formatted}" type="both" dateStyle="full" timeStyle="full" timeZone="PST" var="parsedDateTime"/> Parsed date: <fmt:formatDate value="${parsedDateTime}" type="date" dateStyle="full"/><br> Parsed time: <fmt:formatDate value="${parsedDateTime}" type="time" timeStyle="full"/> </fmt:timeZone>

Page 146: 1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does

146

Example: using browser locale en-us