81
JSP Custom Tags Outline Defined Motivation Tag Types Tag Handlers Tag Library Descriptors Using Tags in JSPs Examples

JSP Custom Tags

Embed Size (px)

Citation preview

Page 1: JSP Custom Tags

JSP Custom Tags

Outline Defined Motivation Tag Types Tag Handlers Tag Library Descriptors Using Tags in JSPs Examples

Page 2: JSP Custom Tags

What are Custom Tags?

A custom tag is a user-defined JSP language element.

JSP custom tags are merely Java classes that implement special interfaces.

Page 3: JSP Custom Tags

What are Custom Tags?

When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.

Page 4: JSP Custom Tags

Motivation

Better Packaging

By improving the separation between business logic and presentation.

Encapsulate common functionality

Over a large number of pages and reuse it. This applies to both HTML presentation and application logic.

Page 5: JSP Custom Tags

Motivation

Reduce number of Scriptlets

Scriptlets are not reusable. Eliminate/reduce number of scriptlets in page.

Simple to use

HTML like syntax, reduces Java code in the page.

Page 6: JSP Custom Tags

Motivation

Im plem entationPresentation

HT M L a n dHT M L - likeJSP ta g s

Ja va Be a n s

C u s to mJSP T a g s

Page 7: JSP Custom Tags

What can they do?

Produce content for a JSP page Access a page’s JavaBeans Introduce new JavaBeans Introduce new scripting variables

Page 8: JSP Custom Tags

Tag Types

Tags without Body Tags with Body

Syntax In HTML

<tagName attributeName="value"

anotherAttributeName="anotherValue"/>

Syntax In HTML

<tagName attributeName="value"

anotherAttributeName="anotherValue">

...tag body...

</tagName>

Page 9: JSP Custom Tags

Tag Types

Tags without Body Tags with Body

Syntax In JSP

<tagLibrary:tagName />

Syntax In JSP

<tagLibrary:tagName>

body

</tagLibrary:tagName>

Page 10: JSP Custom Tags

Tag Handler

A tag handler is an object invoked by the JSP runtime to evaluate a custom tag during the execution of a JSP page that references the tag.

The methods of the tag handler are called by the implementation class at various points during the evaluation of the tag.

Every tag handler must implement a specialized interface.

Page 11: JSP Custom Tags

javax.servlet.jsp.tagext.Tag

All tags must implement Tag interface. Defines methods the JSP runtime

engine calls to execute a tag.

Page 12: JSP Custom Tags

javax.servlet.jsp.tagext.Tag

public interface Tag {public final static int SKIP_BODY = 0;public final static int EVAL_BODY_INCLUDE=1;public final static int SKIP_PAGE = 5;public final static int EVAL_PAGE = 6;

void setPageContext(PageContext pageContext);void setParent(Tag parent);

Tag getParent();

int doStartTag() throws JspException;int doEndTag() throws JspException;void release();}

Page 13: JSP Custom Tags

Interface Tag Fields

static int EVAL_BODY_INCLUDE

          Evaluate body into existing out stream.

static int EVAL_PAGE

          Continue evaluating the page.

static int SKIP_BODY

          Skip body evaluation.

static int SKIP_PAGE

          Skip the rest of the page.

Page 14: JSP Custom Tags

Interface Tag Methods

int doStartTag()

Called by JSP runtime for Tag handler to process the start tag for this instance.

int doEndTag()

Called by JSP runtime after returning from doStartTag(). The body of the action may or may not have been evaluated, depending on the return value of doStartTag().

Page 15: JSP Custom Tags

Interface Tag Methods

Tag getParent() Get the parent (closest enclosing tag handler) for this tag handler.

 void release()

Called on a Tag handler to perform any cleanup operation.

Page 16: JSP Custom Tags

Interface Tag Methods

 void setPageContext(PageContext pc)

Set the current page context. Invoked before doStartTag() to set the page context.

void setParent(Tag parent) Set the parent (closest enclosing tag handler) of this tag handler. Invoked by the JSP runtime, prior to doStartTag(), to pass a tag handler a reference to its parent tag.

Page 17: JSP Custom Tags

Class TagSupport

A utility base class for defining new tag handlers implementing Tag interface.

The TagSupport class implements the Tag and IterationTag interfaces and adds additional convenience methods including getter methods for the properties in Tag

Page 18: JSP Custom Tags

Template for Tag Without Body

import java.io.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

public class HelloTag extends TagSupport {public int doStartTag() throws JspException{

try {// Java code

} catch (IOException ioe) {

Page 19: JSP Custom Tags

Template for Tag Without Body

throw new JspException("Error: " + ioe.getMessage());

}return SKIP_BODY;

}

public int doEndTag() throws JspException {

return EVAL_PAGE;

}

}

Page 20: JSP Custom Tags

Template for Tag With Body

import java.io.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

public class HelloTag extends TagSupport {public int doStartTag() throws JspException{

try {// Java code

} catch (IOException ioe) {

Page 21: JSP Custom Tags

Template for Tag With Body

throw new JspException("Error: " + ioe.getMessage());}return EVAL_BODY_INCLUDE;

}

public int doEndTag() throws JspException {

return EVAL_PAGE;}

}

Page 22: JSP Custom Tags

Tag With Attributes

Also called parameterized tags. Attributes for customizing behavior of

tag. Attributes are modeled as JavaBeans

properties. To add an attribute to tag:

Need a member variable in class to represent the attribute.

Add a setter method for the attribute.

Page 23: JSP Custom Tags

Tag Life Cycle

O btainhandler

S etproper ties

S et attr ibu tevalues

s etP ageContext()s etP arent()

doS tar tT ag ()

P roc es s body

doEndT ag()

EVAL_BO D Y_IN CLUD E

S KIP _BO D Y

S top

releas e()

EVAL_P AG ES KIP _P AG E

releas e()

Continue

Page 24: JSP Custom Tags

Example

A website wants a consistent number and type of fonts. There are 20 developers all with their own opinion on what fonts to use. Custom font tag will need a body, as text will have to go between its start and end tag. The tag should have two attributes to alter its color and size.

Page 25: JSP Custom Tags

MyFontTag.java

package test;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.PageContext;

import javax.servlet.jsp.tagext.TagSupport;

public class MyFontTag extends TagSupport

{

private String size ="2"; // default size is 2

private String color="#0000FF"; // default color is blue

public void setSize(String str) { this.size = str; }

public void setColor(String str) { this.color = str; }

Page 26: JSP Custom Tags

MyFontTag.java

public int doStartTag() throws JspException {

try

{

pageContext.getOut().print("<font face=\"Arial, Helvetica, sans-serif\" size=\""+size+"\" color=\""+color+"\">");

}

catch (Exception e) {

throw new JspException(e.toString());

}

return (EVAL_BODY_INCLUDE);

}

Page 27: JSP Custom Tags

MyFontTag.java

public int doEndTag() throws JspException {

try

{

pageContext.getOut().print("</font>");

}

catch (Exception e) {

throw new JspException(e.toString());

}

return (EVAL_PAGE);

// check with SKIP_PAGE

}

Page 28: JSP Custom Tags

MyFontTag.java

public void release()

{

super.release();

}

}

Note: The font will always be Arial, Helvetica, sans-serif as this is not an attribute in our tag, but explicitly hard coded. Its color and size can be altered.

Page 29: JSP Custom Tags

Tag Library Descriptor

Tag syntax is specified by means of Tag Library Descriptor (TLD)

Specifies mapping between tag names and classes and how the tag will be used by JSP runtime that executes tag.

TLD specifies tag attributes

- Attribute names

- Required vs. optional

- Compile-time vs. run-time values

Page 30: JSP Custom Tags

Tag Library Descriptor

The <shortname> tag specifies how the tag library is going to be referenced from JSP page.

The <uri> tag can be used as a unique identifier for tag library.

Page 31: JSP Custom Tags

Tag Library Descriptor

<bodycontent> values can be

i) empty: tag does not has body

ii) tagdependent: any body of the tag would be handled by the tag itself, and it can be empty.

iii) JSP: meaning that the JSP container should evaluate any body of the tag, but it can also be empty.

Page 32: JSP Custom Tags

Tag Library Descriptor

Tags without bodies must declare that their body content is empty

If contents of tags are JSP, bodycontent should be declared as JSP

bodycontent is tagdependent if tag will interpret the contents of the body as non-JSP (for instance an SQL statement)

Page 33: JSP Custom Tags

Tag Library Descriptor

Body content containing custom and core tags, scripting elements, and HTML text is categorized as JSP; all other types of body content are tagdependent. Note that the value of this element does not affect the interpretation of the body. The bodycontent element is only intended to be used by an authoring tool to present the content of the body.

Page 34: JSP Custom Tags

Tag Library Descriptor

<rtexprvalue> tag is when set to false specifies that no run time evaluation is required.

Request-time attribute values must be JSP expressions:

<css:time timezone=”<%= getTZ()%>”> Only name and tagclass are mandatory

all other are optional.

Page 35: JSP Custom Tags

Mytaglib.tld

<?xml version="1.0"?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.// DTD JSP Tag Library 1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<jspversion>1.1</jspversion>

<shortname>ctag</shortname>

<tag>

<name>myfont</name>

<tagclass>test.MyFontTag</tagclass>

<bodycontent>JSP</bodycontent>

Page 36: JSP Custom Tags

Mytaglib.tld

<attribute>

<name>color</name>

<required>false</required>

<rtexprvalue>false</rtexprvalue>

</attribute>

<attribute>

<name>size</name>

<required>false</required>

<rtexprvalue>false</rtexprvalue>

</attribute>

</tag>

</taglib>

Page 37: JSP Custom Tags

Referencing Tags

1. Reference the tag library descriptor of an unpacked tag library using taglib directive

<%@ taglib uri="/WEB-INF/jsp/mytaglib.tld" prefix="first" %>

2. Reference a JAR file containing a tag library

<%@ taglib uri="/WEB-INF/myJARfile.jar" prefix='first" %>

3. Define a reference to the tag library descriptor from the web-application descriptor (web.xml) and define a short name to reference the tag library from the JSP.

<taglib><taglib-uri>mytags</taglib-uri>

<taglib-location>/WEB-INF/jsp/ mytaglib.tld</taglib-location>

</taglib>

In JSP

<%@ taglib uri=“mytags" prefix='first" %>

Page 38: JSP Custom Tags

The Custom Tag Library Architecture

                                                                                                                    

                                                                                

Page 39: JSP Custom Tags

CustomTag1.jsp

<HTML>

<HEAD><TITLE>Tag Lib Example</TITLE></HEAD>

<BODY>

<%@ taglib uri="mytaglib.tld" prefix="ctag" %>

To make use of custom tag, in JSP write… <BR>

<ctag:myfont>With default attributes</ctag:myfont>

<BR>Or if you want to change the values from default <BR>

<ctag:myfont color="#FF0000" size="4">

With given attributes

</ctag:myfont>

</BODY>

</HTML>

Page 40: JSP Custom Tags

Page Compilation

Pa g eC o m p ile r

taglib d ire c tive ? n e w T L D ? lo a d T L D

cu s to m ta g ? va lid a te a ttr ib u te syn ta x

T a g Extra In fo ? id e n tify sc r ip tin g va r ia b le s

a sso c ia te va r ia b le n a m e s a n d c la sse s

Page 41: JSP Custom Tags

Page Execution

R e q u e s t

R e sp o n se

taglib d ire c tive ? n o a c tio n re q u ire d

cu s to m ta g ? n e w ta g ?

o b ta in h a n d le r fro m p o o l

lo a d ta g h a n d le r

a d d in s ta n ce (s ) to re so u rce p o o l

in it ia lize h a n d le r fo r ta g

e xe cu te h a n d le r

re tu rn h a n d le r to p o o l

Page 42: JSP Custom Tags

Running JSP

1. Create folder “test” in ApacheHome\webapps\examples\jsp.

2. Store file MyFontTag.java in folder “test”.

3. Include servlet.jar in classpath. Location is ApacheHome\common\lib\servlet.jar

4. Compile MyFontTag.java

5. Store Mytaglib.tld in folder “test”

6. Set classpath ApacheHome\webapps\examples\jsp in a new window before starting tomcat server.

7. Set classpath ApacheHome\common\lib\servlet.jar in a new window before starting tomcat server.

8. Start tomcat server

9. Run JSP

http://localhost:7001/examples/jsp/test/CustomTag1.jsp

Page 43: JSP Custom Tags

Result

To make use of custom tag, in JSP write…

With default attributes

Or if you want to change the values from default

With given attributes

Page 44: JSP Custom Tags

Notes

For large project with many developers and many custom tags in TLD is to create a jar (e.g MyTagLib.jar) file containing the custom tag classes and the TLD (TLD “taglib.tld”, and it should be placed into /META-INF of jar file)

Once the jar file is in class path custom tags can be referenced in JSP via

<%@ taglib uri="MyTag.jar" prefix=“ctag" %>

Page 45: JSP Custom Tags

Notes

In webapps/examples/WEB-INF/web.xml add entry

<taglib>

<taglib-uri>MyTag</taglib-uri>

<taglib-location>/jsp/test/mytaglib.tld

</taglib-location>

</taglib>

In JSP

<%@ taglib uri="MyTag" prefix=“ctag" %>

Page 46: JSP Custom Tags

Tag Library

A tag library is a collection of JSP custom tags.

META-INF

MANIFEST.MF

taglib.tld

directoriescontainingtag handlerpackages

TagLibrary

JAR

Page 47: JSP Custom Tags

Tags With Body

A tag handler for a tag with a body is implemented differently depending on whether the body needs to be evaluated once or multiple times.

Body Evaluation

Single Evaluation

Multiple Evaluation

E.g. of iteration

Iterate rows, query, search results

Page 48: JSP Custom Tags

Tags With Body

Single Evaluation Multiple Evaluation

Implement interface Tag Implement interface BodyTag

doStartTag method needs to return EVAL_BODY_INCLUDE, and if it does not need to be evaluated at all then it should return SKIP_BODY.

Typically, override doInitBody and doAfterBody methods. The doInitBody is called after the body content is set but before it is evaluated, and the doAfterBody is called after the body content is evaluated.

Page 49: JSP Custom Tags

Body Evaluation

A tag handler for a tag with a body is implemented differently depending on whether the body needs to be evaluated once or multiple times.

Body Evaluation

Single Evaluation

Multiple Evaluation

Page 50: JSP Custom Tags

BodyTag Interface

Complex tags implement the BodyTag interface

- Generate page content

- Conditionally execute body content

- Process content generated by body

- Repeat execution of body content

- Conditionally halt page execution BodyTagSupport class provides default

implementation

Page 51: JSP Custom Tags

BodyTag Interface

The BodyTag interface extends Tag by defining additional methods that let a tag handler access its body. The interface provides three new methods:

- setBodyContent: Creates body content and adds to the tag handler

- doInitBody: Called before evaluation of the tag body

- doAfterBody: Called after evaluation of the tag body

Page 52: JSP Custom Tags

BodyTag Interface

Tag

Iteration Tag

Body Tag

TagSupport

implementsBodyTagSupport

implements

Page 53: JSP Custom Tags

BodyTag Life Cycle

O btainhandler

S etproper ties

S et attr ibu tevalues

s etP ageContex t()s etP aren t()

doS tar tT ag()

In itializebody c onten t

doEndT ag()

EVAL_BO D Y_T AG

S KIP _BO D Y

S top

releas e()

EVAL_P AG ES KIP _P AG E

releas e()

Continue

s etBodyConten t( )doIn itBody()

P roc es s body

doAfterBody()S KIP _BO D Y EVAL_BO D Y_T AG

Page 54: JSP Custom Tags

Single Evaluation

package test;

import java.io.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

public class ToLowerCaseTag extends BodyTagSupport {

public int doAfterBody() throws JspException {

try {

BodyContent bc = getBodyContent();

String body = bc.getString();

Page 55: JSP Custom Tags

Single Evaluation

JspWriter out = bc.getEnclosingWriter();

if(body != null) {

out.print(body.toLowerCase());

}

} catch(IOException ioe) {

throw new JspException(ioe.getMessage());

}

return SKIP_BODY;

}

}

Page 56: JSP Custom Tags

Single Evaluation

TLD

<tag>

<name>tolowercase</name>

<tagclass>test.ToLowerCaseTag</tagclass>

<bodycontent>JSP</bodycontent>

<info>To lower case tag</info>

</tag>

Page 57: JSP Custom Tags

Single Evaluation

<HTML>

<HEAD><TITLE>To Lower Case Example </TITLE> </HEAD>

<BODY>

JSP Custom Tag Programming<BR>

<%@ taglib uri="mytaglib.tld" prefix="ctag" %>

<ctag:tolowercase>

JSP Custom Tag Programming

</ctag:tolowercase>

</BODY>

</HTML>

Page 58: JSP Custom Tags

Single Evaluation

Result

JSP Custom Tag Programmingjsp custom tag programming

Page 59: JSP Custom Tags

Single Evaluation

Result

JSP Custom Tag Programmingjsp custom tag programming

Page 60: JSP Custom Tags

Single Evaluation

<HTML>

<HEAD><TITLE>To Lower Case Example </TITLE> </HEAD>

<BODY>

JSP Custom Tag Programming<BR>

<%@ taglib uri="mytaglib.tld" prefix="ctag" %>

<ctag:tolowercase>

<ctag:myfont color="#FF0000" size="4">

JSP Custom Tag Programming

</ctag:myfont>

</ctag:tolowercase>

</BODY>

</HTML>

Page 61: JSP Custom Tags

Single Evaluation

Result

JSP Custom Tag Programming

jsp custom tag programming

Page 62: JSP Custom Tags

Multiple Evaluation Example

...

taglib uri="mytags" prefix="codecamp"

%>

<OL>

<!-- Repeats N times. A null reps value

means repeat once. -->

<codecamp:repeat reps='<%=

request.getParameter("repeats") %>'>

<LI><codecamp:prime length="40" />

</codecamp:repeat>

</OL>...

Page 63: JSP Custom Tags

Multiple Evaluation

package test;

import java.io.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

public class IterTag extends BodyTagSupport {

int times = 0;

BodyContent bodyContent;

public void setTimes(int times) { this.times = times; }

public int doStartTag() throws JspException

{

return times >1?EVAL_BODY_AGAIN:SKIP_BODY;

}

Page 64: JSP Custom Tags

Multiple Evaluation

public void setBodyContent(BodyContent bodyContent) {

this.bodyContent = bodyContent;

}

public int doAfterBody() throws JspException {

if (times >1) {

times--;

return EVAL_BODY_AGAIN;

} else

{

return SKIP_BODY;

}

}

Page 65: JSP Custom Tags

Multiple Evaluation

public int doEndTag() throws JspException {

try {

if(bodyContent != null) {

bodyContent.writeOut

(bodyContent.getEnclosingWriter());

}

} catch(IOException e) {

throw new JspException(e.getMessage());

}

return EVAL_PAGE;

}

}

Page 66: JSP Custom Tags

Multiple Evaluation

<tag>

<name>iter</name>

<tagclass>test.IterTag</tagclass>

<bodycontent>JSP</bodycontent>

<info>Tag with body and parameter</info>

<attribute>

<name>times</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

</tag>

Page 67: JSP Custom Tags

Multiple Evaluation

<HTML><HEAD><TITLE>To Lower Case Example</TITLE></HEAD>

<BODY>

JSP Custom Tag Programming<BR>

<%@ taglib uri="mytaglib.tld" prefix="ctag" %>

<ctag:iter times="5">

<ctag:tolowercase>

<ctag:myfont color="#FF0000" size="4">

JSP Custom Tag Programming <BR>

</ctag:myfont>

</ctag:tolowercase>

</ctag:iter>

</BODY>

</HTML>

Page 68: JSP Custom Tags

Multiple Evaluation

Result

JSP Custom Tag Programming

jsp custom tag programming

jsp custom tag programming

jsp custom tag programming

jsp custom tag programming

jsp custom tag programming

Page 69: JSP Custom Tags

Cooperating Tags

<tlt:connection id="con01" ...>    

<x:query id="balances">       

SELECT account, balance FROM acct_table where customer_number = <%=request.getCustno()%>    

</x:query>

</tlt:connection>

Page 70: JSP Custom Tags

Examples

Ex. For displaying today’s date according to locale.

<%@ taglib uri="/WEB-INF/lib/DateTagLib.tld" prefix="abc" %>

<HTML>

<HEAD><TITLE>Date tag example</TITLE> </HEAD>

<BODY>

Today is <b><abc:displayDate /></b>

</BODY>

</HTML>

Page 71: JSP Custom Tags

Scripting variables

package test;

import java.util.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

public final class SecondTag implements Tag {

private PageContext pc = null;

public void setPageContext(PageContext p) {

pc = p;

}

public void setParent(Tag t) {}

public Tag getParent() { return null; }

Page 72: JSP Custom Tags

Scripting variables

public int doStartTag() throws JspException {

Calendar cal = Calendar.getInstance();

pc.setAttribute("time", cal.getTime().toString());

return EVAL_BODY_INCLUDE;

}

public int doEndTag() throws JspException {

return EVAL_PAGE;

}

public void release() { pc = null; }

}

Page 73: JSP Custom Tags

Scripting variables

package test;

import javax.servlet.jsp.tagext.*;

public class SecondTagTEI extends TagExtraInfo {

public VariableInfo[] getVariableInfo(TagData data) {

return new VariableInfo[] {

new VariableInfo("time", "java.lang.String",

true, VariableInfo.NESTED)

};

}

}

Page 74: JSP Custom Tags

Scripting variables

<tag>

<name>secondtag</name>

<tagclass>test.SecondTag</tagclass>

<teiclass>test.SecondTagTEI</teiclass>

<bodycontent>JSP</bodycontent>

<info>Your second JSP Tag</info>

</tag>

Page 75: JSP Custom Tags

Scripting variables

<html><head<title>SecondTag</title></head>

<body>

<%@ taglib uri="mytaglib.tld" prefix="star"%>

<star:secondtag>

<p>Date value retrieved from JSP Tag:<%= time %></p>

</star:secondtag>

</body>

</html>

Page 76: JSP Custom Tags

Examples

JSP tags are especially suited for repetitive tasks such as looping over an array, doing browser checking, and validation. Creating hyperlinks is another such repetitive task.

Multi-destination hyperlinks.

Page 77: JSP Custom Tags

Examples

Page 78: JSP Custom Tags

Examples

<%@ taglib uri="http://jakarta.apache.org/taglibs/dbtags" prefix="sql" %> 

<%-- open a db connection --%> 

<sql:connection id="conn1"> <sql:url>jdbc:mysql://localhost/test</sql:url> <sql:driver>org.gjt.mm.mysql.Driver</sql:driver>

</sql:connection> 

Page 79: JSP Custom Tags

Examples

<%-- insert a row into the database --%> 

<sql:statement id="stmt1" conn="conn1">

<%-- set the SQL query --%>

<sql:query>insert into counters(page,hitCount) values('<%=request.getRequestURI()%>', 0)

</sql:query>

Page 80: JSP Custom Tags

Examples

<%-- the insert may fail, but the page will continue --%>

<sql:execute ignoreErrors="true"/>

</sql:statement>

Page 81: JSP Custom Tags

Examples

<%-- update the hit counter --%> 

<sql:statement id="stmt1" conn="conn1">

<%-- set the SQL query --%>

<sql:query>update counters set hitCount = hitCount + 1 where page like '<%=request.getRequestURI()%>'

</sql:query>

<sql:execute/> <%– Execute query --%>

</sql:statement>