Jsp 1.2 Custom Tags

  • July 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Jsp 1.2 Custom Tags as PDF for free.

More details

  • Words: 4,502
  • Pages: 115
JSP 1.2 Custom Tags 1

Disclaimer & Acknowledgments ●





Even though Sang Shin is a full-time employees of Sun Microsystems, the contents here are created as his own personal endeavor and thus does not reflect any official stance of Sun Microsystems. Sun Microsystems is not responsible for any inaccuracies in the contents. Acknowledgements – The slides, speaker notes, and example code of this presentation are created from ● “Core Servlets and JavaServer Pages” book written by Marty Hall ● “Custom Tags” section of Java WSDP 1.2 tutorial written by Stephanie Bodoff of Sun Microsystems – Many slides are borrowed from “Sevlet/JSP” codecamp material authored by Doris Chen of Sun Microsystems 2

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

3

Agenda I ● ● ●





Evolution of Web-tier technology What is and why custom tags? Components that make up custom tag architecture How to build, configure, and deploy custom tag library? How does it work? 4

Agenda II ●

Usage scenarios of custom tags (in the increasing order of complexity) – – – – – – –

Defining a tag without attributes or tag bodies Assigning attributes to tags Including tag body Optionally including tag body Manipulating tag body Including or manipulating tag body multiple times Using nested tags 5

Evolution of Web tier technology 6

Web Application Designs

7

Where does custom tags fit in?

8

Standard Action Tags (or Tags) ●

<jsp:useBean> – Instantiate JavaBean object



<jsp:getProperty> – Allow accessing bean properties



<jsp:setProperty> – Allow setting bean properties

9

Standard Action Tags (or Tags) ●

<jsp:forward> – Forwards request to another HTML page, JSP, or servlet



<jsp:include> – Includes output of another JSP file



<jsp:plugin> – Downloads Java plugin to browser to execute applet or bean

10

What is a Custom Tag? 11

What is a Custom Tag? ●

● ●

User defined JSP language elements (as opposed to standard tags) Encapsulates recurring tasks Distributed in a “custom made” tag library

12

Custom Tags Can ●

● ● ●

Be customized via attributes passed from the calling JSP page Pass variables back to the calling page Access all the objects available to JSP pages Communicate with each other –



You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag

Be nested within one another and communicate via private variables 13

Custom Tag Examples ● ● ● ● ● ●

Getting/setting Implicit objects Processing forms Accessing database Flow control Iterations Many more

14

Ready-to-usable Custom Tag Library ●

Java Standard Tag Library (JSTL) – – – –



Tags for setting/getting attributes, iteration, etc Tags for database access Tags for internationalized formatting Tags for XML

Jakarta-Taglibs

15

Why Custom Tags? 16

Why Custom Tags? ●

Separate presentation from business (and other functionality) logic – page authors author presentation – Business logic developers create custom tags



Encapsulate business logic – Reusable & Maintainable



Help page authors – Page authors use simpler syntax



Provide – Portable semantics 17

Custom Tags against JavaBeans ●

Pros – –



Custom tags can manipulate JSP contents while beans cannot Complex operations can be reduced to a significantly simpler form with custom tags than beans

Cons –

Custom tags require quite a bit of more work to set up than do beans

source: more Servlets and JSP[2]

18

Quick Introduction on Components that make up Custom tag architecture (in JSP 1.2) 19

Three things make up custom tag architecture ●

Tag handler class –



Tag library descriptor (TLD) –



Defines tag's behavior Maps XML elements to tag handler class

JSP file (user of custom tags) –

Uses tags

20

Steps for implementing & using & deploying custom tags ●

Implementing custom tags – – –



Using 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) Write JSP pages that use tags

Deploying custom tags as part of web app –

Configure and deploy tag library along with JSP pages

21

Tag handler class ●

Implements interface – –



Usually extends utility class – –



javax.servlet.jsp.tagext.Tag or javax.servlet.jsp.tagext.Bodytag interface javax.servlet.jsp.tagext.TagSupport or javax.servlet.jsp.tagext.BodyTagSupport class

Located in the same directory as servlet class files –

/WEB-INF/classes/<package-directory-structure> 22

Example: Tag Handler (page 1) ExampleTag.java package moreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; /** 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. *

* Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */

23

Example: Tag Handler (page 2) ExampleTag.java public class ExampleTag extends TagSupport { public int doStartTag() { try { JspWriter out = pageContext.getOut(); out.print("Custom tag example " + "(moreservlets.tags.ExampleTag)"); } catch(IOException ioe) { System.out.println("Error in ExampleTag: " + ioe); } return(SKIP_BODY); } }

24

Tag Library Descriptor (TLD) ●

XML file that describes – – – –





Container knows which tag is associated with which tag handler class via this file Located –



tag name bodycontent attributes tag handler class

Usually under WEB-INF directory

Custom location can specified in JSP file –

Via uri attribute of taglib directive

25

Example: TLD (page 1) msajsp-tags.tld 1.0 <jspversion>1.1 <shortname>msajsp-tags A tag library from More Servlets and JavaServer Pages, http://www.moreservlets.com/. 26

Example: TLD (page 2) msajsp-tags.tld example moreservlets.tags.ExampleTag empty Simplest example: inserts one line of output simplePrime moreservlets.tags.SimplePrimeTag empty Outputs a random 50-digit prime. ...
27

What is Tag Library? ●

Is a collection of related tags –



Tag(s) can be packaged in a Tag Library

Typically packaged as a jar file containing – A tag library descriptor (TLD) • e.g. META-INF/taglib.tld – *.class files for the tag handler class(es) – Any additional associated resource(s)

28

JSP page ● ●

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

29

Declaring a tag library ● ●

Include taglib directive before tags are used Syntax – – –

<%@ taglib prefix="myprefix" uri=”myuri” %> prefix: identifies the tag library uri: uniquely identifies the tag library descriptor (TLD) directly or indirectly

30

Custom Tag Syntax in a JSP page <prefix:tag attr1="value" ... attrN="value" /> or <prefix:tag attr1="value" ... attrN="value" > body prefix: distinguishes tag library tag: identifies a tag (within the tag library) attr1 ... attrN: modify the behavior of the tag 31

Example: JSP page SimpleExample.jsp <%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %> <TITLE><msajsp:example />

<msajsp:example />

<msajsp:example />

32

Example: Accessing SimpleExample.jsp

33

How to build, configure and deploy tag library

34

Source Directory Structure ●

Use the following source directory structure (as in J2EE 1.4 Tutorial's web/iterator directory) –

<j2ee14tutorial-install>/j2eetutorial14/examples/web ● iterator – 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 35

Build Directory Structure (under build or dist directory) ●

Use the following build directory structure (as in J2EE 1.4 Tutorial's web/iterator directory) –

<j2eetutorial14-install>/j2eetutorial14/examples/web ● iterator – build (unpacked *.war file) – dist (packed *.war file)

36

Usage Scenarios of Custom Tags (in JSP 1.2) 37

Usage Scenarios of Custom Tags ●

Defining a basic tag –

● ● ● ● ●



A tag without attributes or tag bodies

Assigning attributes to tags Including tag body Optionally including tag body Manipulating tag body Including or manipulating tag body multiple times Using nested tags 38

Usage Scenarios of Custom Tags ● ● ●



Bundling listeners with tag libraries Checking syntax with TagLibraryValidator Handling Exceptions with TryCatchFinally interface Looping without generating BodyContent

39

Defining a basic tag (We already saw an example.) 40

Defining a basic tag ● ● ●

A tag without attributes or body Extend TagSupport class All you have to do is to override doStartTag () method –



doStartTag() method defines code that gets called at request time at the place where the element's start tag is found doStartTag() returns SKIP_BODY since the tag does not have a body ●

It instructs the container to ignore any body content between start and end tags 41

Assigning attributes to tags

42

Why assigning attributes to tags? ●



Provides a way to pass attribute/value pairs from JSP pages to custom tag handlers Custom tag handlers can use them in whatever business logic they have

43

Tag handler class ●

Use of an attribute X in a JSP page results in a call to a method setX() in the tag handler class –

Tag handler must implement setX() method public void setX(String value1){ doSomethingWith(value1); }

44

Example: Tag Handler (page 1) SimplePrimeTag.java import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; import java.math.*; import moreservlets.*; /** 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.) *

* Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */ 45

Example: Tag Handler (page 2) SimplePrimeTag.java public class SimplePrimeTag extends TagSupport { protected int len = 50; public int doStartTag() { try { JspWriter out = pageContext.getOut(); BigInteger prime = Primes.nextPrime(Primes.random(len)); out.print(prime); } catch(IOException ioe) { System.out.println("Error generating prime: " + ioe); } return(SKIP_BODY); } }

46

Example: Tag Handler (page 3) PrimeTag.java package moreservlets.tags; /** Generates an N-digit random prime (default N = 50). * Extends SimplePrimeTag, adding a length attribute * to set the size of the prime. The doStartTag * method of the parent class uses the len field * to determine the length of the prime. *

* Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */

47

Example: Tag Handler (page 4) PrimeTag.java public class PrimeTag extends SimplePrimeTag { public void setLength(String length) { try { len = Integer.parseInt(length); } catch(NumberFormatException nfe) { len = 50; } } /** Servers are permitted to reuse tag instances * once a request is finished. So, this resets * the len field. */ public void release() { len = 50; } }

48

TLD ●



Attributes must be declared inside tag element by means of attribute sub-elements Attribute element has 5 sub-elements of its own – – – – –

name (required) required (required) rtexprvalue (optional) type (optional) example (optional) 49

TLD: Attribute's rtexprvalue/type subelements ●

rtexprvalue (optional) –

true if attribute value can be <%= expression %> ●

– ●

attribute value can be determined at request time

false if attribute value is a fixed string (default)

type (optional) – –

specifies the class to which the value of the rtexprvalue should be typecast only legal when rtexprvalue is set to true

50

Example: TLD (page 1) 1.0 <jspversion>1.1 <shortname>msajsp-tags A tag library from More Servlets and JavaServer Pages, http://www.moreservlets.com/.

51

Example: TLD (page 2) ... prime moreservlets.tags.PrimeTag empty Outputs a random N-digit prime. length <required>false ...


52

Example: JSP Page (PrimeExample.jsp) <TITLE>Some N-Digit Primes

Some N-Digit Primes

<%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>
  • 20-digit: <msajsp:prime length="20" />
  • 40-digit: <msajsp:prime length="40" />
  • 60-digit: <msajsp:prime length="60" />
  • Default (50-digit): <msajsp:prime />
53

Example: Accessing PrimeExample.jsp

54

Including Tag Body

55

Including Tag body ● ● ●



<prefix:tagname>body Body content contains typical JSP constructs JSP constructs inside of body content get translated at page translation time In this usage pattern, we are just including body content without any modification

56

Tag handler class ●



doStartTag() method should return EVAL_BODY_INCLUDE doEndTag() gets called after body is evaluated – –

return EVAL_PAGE for continued processing return SKIP_PAGE for aborting processing rest of the page

57

Example: Tag Handler (page 1) HeadingTag.java package moreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; /** 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. *

* Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */

58

Example: Tag Handler (page 2) HeadingTag.java public class HeadingTag extends TagSupport { private String bgColor; // The one required attribute private String color = null; private String align="CENTER"; private String fontSize="36"; private String fontList="Arial, Helvetica, sans-serif"; private String border="0"; private String width=null; public void setBgColor(String bgColor) { this.bgColor = bgColor; } public void setColor(String color) { this.color = color; } ...

59

Example: Tag Handler (page 3) HeadingTag.java public int doStartTag() { try { JspWriter out = pageContext.getOut(); out.print("

"); out.print("<SPAN STYLE=\"" + "font-size: " + fontSize + "px; " + "font-family: " + fontList + "; "); if (color != null) { out.println("color: " + color + ";"); } out.print("\"> "); // End of <SPAN ...> } catch(IOException ioe) { System.out.println("Error in HeadingTag: " + ioe); } return(EVAL_BODY_INCLUDE); // Include tag body }

60

Example: Tag Handler (page 4) HeadingTag.java public int doEndTag() { try { JspWriter out = pageContext.getOut(); out.print("
"); } catch(IOException ioe) { System.out.println("Error in HeadingTag: " + ioe); } return(EVAL_PAGE); // Continue with rest of JSP page } }

61

TLD ●

The bodycontent element should contain the value JSP –

JSP

62

Example: TLD ... heading moreservlets.tags.HeadingTag JSP Outputs a 1-cell table used as a heading. bgColor <required>true color <required>false ...

63

Example: JSP Page (HeadingExample.jsp) <TITLE>Some Tag-Generated Headings <%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %> <msajsp:heading bgColor="#C0C0C0"> Default Heading

<msajsp:heading bgColor="BLACK" color="WHITE"> White on Black Heading 64

Example: JSP Page (HeadingExample.jsp)

<msajsp:heading bgColor="#EF8429" fontSize="60" border="5"> Large Bordered Heading

<msajsp:heading bgColor="CYAN" width="100%"> Heading with Full-Width Background

<msajsp:heading bgColor="CYAN" fontSize="60" fontList="Brush Script MT, Times, serif"> Heading with Non-Standard Font

65

66

Optionally Including Tag Body

67

Optionally Including Tag body ●



Decision of usage of body content is decided at request time Body content is not modified

68

Tag handler class ●

doStartTag() method returns either EVAL_BODY_INCLUDE or SKIP_BODY –



depending on the value of some request time expression, for example

Call getRequest() from pageContext field of TagSupport –

Typecast the return of getRequest() to HttpServletRequest since getRequest() returns ServletRequest type

69

Example: Tag Handler (page 1) DebugTag.java package moreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; import javax.servlet.*; /** A tag that includes the body content only if * the "debug" request parameter is set. *

* Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */

70

Example: Tag Handler (page 2) DebugTag.java public class DebugTag extends TagSupport { public int doStartTag() { ServletRequest request = pageContext.getRequest(); String debugFlag = request.getParameter("debug"); if ((debugFlag != null) && (!debugFlag.equalsIgnoreCase("false"))) { return(EVAL_BODY_INCLUDE); } else { return(SKIP_BODY); } } }

71

Example: TLD ... debug moreservlets.tags.DebugTag JSP Includes body only if debug param is set. ...

72

Example: JSP Page (DebugExample.jsp) <TITLE>Using the Debug Tag

Using the Debug Tag

<%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %> Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.

73

Example: JSP Page (DebugExample.jsp) <msajsp:debug> Debug:

  • Current time: <%= new java.util.Date() %>
  • Requesting hostname: <%= request.getRemoteHost() %>
  • Session ID: <%= session.getId() %>

Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.

74

DebugTag without “debug” input parameter

75

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

76

Manipulating Tag Body

77

Tag handler class ●



Tag handler class should extend BodyTagSupport class BodyTagSupport class has 2 convenience methods –

doAfterBody(): override this method in order to manipulate the tag body ● ●



return SKIP_BODY if no further body processing is needed return EVAL_BODY_TAG (JSP 1.1) or EVAL_BODY_AGAIN (JSP 1.2) if the body content needs to be evaluated and handled again

getBodyContent(): returns BodyContent object 78

BodyContent class ●

● ●

An encapsulation of the evaluation of the body A subclass of JspWriter BodyContent class has 3 methods – – –

getEnclosingWriter(): returns JspWriter getReader(): returns a Reader that can read tag body getString(): returns a String containing entire tag body

79

Example: Tag Handler (page 1) FilterTag.java package moreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; import moreservlets.*; /** A tag that replaces <, >, ", and & with their HTML * character entities (<, >, ", and &). * After filtering, arbitrary strings can be placed * in either the page body or in HTML attributes. *

* Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */ 80

Example: Tag Handler (page 2) FilterTag.java public class FilterTag extends BodyTagSupport { public int doAfterBody() { BodyContent body = getBodyContent(); String filteredBody = ServletUtilities.filter(body.getString()); try { JspWriter out = body.getEnclosingWriter(); out.print(filteredBody); } catch(IOException ioe) { System.out.println("Error in FilterTag: " + ioe); } // SKIP_BODY means we're done. If we wanted to evaluate // and handle the body again, we'd return EVAL_BODY_TAG // (JSP 1.1/1.2) or EVAL_BODY_AGAIN (JSP 1.2 only) return(SKIP_BODY); } } 81

Example: TLD ... filter moreservlets.tags.FilterTag JSP Replaces HTML-specific characters in body. ...

82

Example: JSP Page (FilterExample.jsp) <TITLE>HTML Logical Character Styles

HTML Logical Character Styles

Physical character styles (B, I, etc.) are rendered consistently in different browsers. Logical character styles, however, may be rendered differently by different browsers. Here's how your browser (<%= request.getHeader("User-Agent") %>) renders the HTML 4.0 logical character styles:



83

Example: JSP Page (FilterExample.jsp) <%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>

ExampleResult
<msajsp:filter> <EM>Some emphasized text.
<STRONG>Some strongly emphasized text.
Some code.
<SAMP>Some sample text.
Some keyboard text.
A term being defined.
A variable.
A citation or reference.
<EM>Some emphasized text.
<STRONG>Some strongly emphasized text.
Some code.
<SAMP>Some sample text.
Some keyboard text.
A term being defined.
A variable.
A citation or reference.


84

To be added

85

Including or Manipulating Tag Body Multiple Times

86

Tag handler class ●



Tag handler class should extend BodyTagSupport class doAfterBody() now returns EVAL_BODY_TAG (EVAL_BODY_AGAIN in JSP 1.2)

87

Example: Tag Handler (page 1) RepeatTag.java package moreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; /** A tag that repeats the body the specified * number of times. *

* Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */

88

Example: Tag Handler (page 2) RepeatTag.java public class RepeatTag extends BodyTagSupport { private int reps; public void setReps(String repeats) { try { reps = Integer.parseInt(repeats); } catch(NumberFormatException nfe) { reps = 1; } }

89

Example: Tag Handler (page 3) RepeatTag.java public int doAfterBody() { if (reps-- >= 1) { BodyContent body = getBodyContent(); try { JspWriter out = body.getEnclosingWriter(); out.println(body.getString()); body.clearBody(); // Clear for next evaluation } catch(IOException ioe) { System.out.println("Error in RepeatTag: " + ioe); } // Replace EVAL_BODY_TAG with EVAL_BODY_AGAIN in JSP 1.2. return(EVAL_BODY_TAG); } else { return(SKIP_BODY); } } 90

Example: TLD ... repeat moreservlets.tags.RepeatTag JSP Repeats body the specified number of times. reps <required>true true ...

91

Example: JSP Page (RepeatExample.jsp) <TITLE>Some 40-Digit Primes

Some 40-Digit Primes

Each entry in the following list is the first prime number higher than a randomly selected 40-digit number.

92

Example: JSP Page (RepeatExample.jsp) <%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>
    <msajsp:repeat reps='<%= request.getParameter("repeats") %>'>
  1. <msajsp:prime length="40" />


93

To be added

94

More detailed information on How to declare tag library using taglib directive

95

Declaring a tag library: uri attribute (3 different ways - 2 on this slide) ●

Direct reference to TLD file –



<%@ taglib prefix="tlt" uri="/WEB-INF/iterator.tld"%>

Indirect reference to TLD file using a logical name – –

<%@ taglib prefix="tlt" uri="/tlt"%> Mapping of the logical name to path to the TLD file has to be defined in web.xml <jsp-config> /tlt /WEB-INF/iterator.tld

96

Declaring a tag library: uri attribute (3 different ways - 1 on this slide) ●

Absolute URI - examples of JSTL tag libraries <%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="xml" uri="http://java.sun.com/jsp/jstl/xml"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

97

More detailed information on How to Configure tag library with Web application 98

Configuring tag library with individual Web app ●

In unpacked form – –



tag handler classes are packaged under the /WEB-INF/classes/ directory *.tld file under the /WEB-INF/ directory

In packaged form (*.jar file) –

*.jar file is in the /WEB-INF/lib/ directory

99

How does it Work?

100

How does it work? ●

JSP translator locates the TLD file via uri attribute of taglib directive –



The TLD file describes the binding between an action (tag handler) and a Tag

Using a tag in a JSP page generates the appropriate servlet code –

The servlet code contains tag handler

101

Sequence of Calls from Container

102

TagSupport Implements Tag Interface

103

doStartTag() and doEndTag() ●

doStartTag() – Processes starting element (semantics) – Returns EVAL_BODY_INCLUDE to process body – Returns SKIP_BODY to skip body



doEndTag() – Completes element processing (flush) – Returns EVAL_PAGE to continue processing – Returns SKIP_PAGE to terminate processing



Both can throw JspException 104

Calling Sequence from the Container Obtain Obtain handler handler

Set Setproperties properties setPageContext( ) setParent( )

doStartTag( )

Set Setattribute attribute values values

Eval_body_include Process Processbody body

Skip_body Skip_page

doEndTag( )

Eval_page

Release( Release())

Release( Release() )

Stop

Continue Continue

105

How Is a Tag Invoked? ●



● ● ●

JSP technology creates (or reuses) a Tag class instance associated with the element in the page source – Class is named in the TLD Container calls setPageContext() and setParent() – parent (possibly null, unless nested) – PageContext provides access to: request, response, out, session, page and attributes Container calls setX() methods for attributes specified Container calls doStartTag() and doEndTag() Container invokes release() to free Tag instance for reuse 106

How Is a Tag Invoked? setPageContext() setParent()

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



setAttr1(“values1”)



setAttr2(“value2”)



doStartTag( )



setBodyContent( )



doInitBody( )



doAfterBody( )



doEndTag( )

107

JSP Page Response Output ●



The output of the page is written into a JSPWriter provided by the page implementation This is flushed to the output stream of the ServletResponse.



Output is buffered in the JSPWriter by default.



Tags output to nested JSPWriter streams.

108

BodyTag, BodyTagSupport For manipulating or evaluating body multiple times, use BodyTagSupport which is BodyTag type • Example of iteration: – such as order rows, search results and etc •

109

How Does BodyTag Work?

110

BodyContent

111

Manipulating BodyContent (1) ●



● ● ●

JSP technology creates a nested stream (BodyContent) to contain the body text The BodyContent is passed to the BodyTag via setBodyContent() doStartBody() is invoked doInitBody() is invoked The body text is evaluated into the BodyContent 112

Manipulating BodyContent (2) ●

doAfterBody() is invoked: – It must process the content of the nested stream and write to nesting stream (out) – It can cause the page to be re-evaluated (to support iterative tags) by returning EVAL_BODY_TAG



Invoke doEndTag().

113

BodyTag Method Semantics ●

doStartTag(): – Same as Tag semantic, except: • Returns EVAL_BODY_TAG to process body



doBodyInit(): – Prepare to process body



doAfterBody() : – Handle processed body in BodyContent – Return EVAL_BODY_TAG to reprocess



DoEndTag() : – Same as Tag Semantics 114

Passion!

115

Related Documents

Jsp 1.2 Custom Tags
July 2020 7
Jsp Custom Tags
November 2019 9
07 Basic Custom Tags
November 2019 8
07-basic-custom-tags
July 2020 8
1creating Custom Tags
November 2019 7