Creating Custom JSP TagCreating Custom JSP Tag Libraries...

33
© 2008 Marty Hall Creating Custom JSP Tag Creating Custom JSP Tag Libraries: The Basics Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2 © 2008 Marty Hall For live Ajax & GWT training, see training t htt // lt / courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Courses developed and taught by Marty Hall Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate, EJB3, Ruby/Rails Contact hall@coreservlets.com for details

Transcript of Creating Custom JSP TagCreating Custom JSP Tag Libraries...

Page 1: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

© 2008 Marty Hall

Creating Custom JSP TagCreating Custom JSP Tag Libraries: The Basics

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.2

© 2008 Marty Hall

For live Ajax & GWT training, see training t htt // l t /courses at http://courses.coreservlets.com/.

Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at publicServlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site

at your organization.

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

y g• Courses developed and taught by Marty Hall

– Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics• Courses developed and taught by coreservlets.com experts (edited by Marty)

– Spring, Hibernate, EJB3, Ruby/Rails

Contact [email protected] for details

Page 2: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Agendag

• Java-based tagsg– Components of a tag library– Basic tags

T h ib– Tags that use attributes– Tags that use body content– Tags that optionally use body contentTags that optionally use body content

• JSP-based tags (tag files)– Components of a tag libraryp g y– Basic tags– Tags that use attributes

Java EE training: http://courses.coreservlets.com

– Tags that use body content

5

Uses of JSP Constructs

• Scripting elements calling servletScripting elements calling servlet code directly

• Scripting elements calling servlet

SimpleApplication

g gcode indirectly (by means of utility classes)B• Beans

• Servlet/JSP combo (MVC)MVC ith JSP i l• MVC with JSP expression language

• Custom tagsMVC ith b t t d

ComplexApplication

Java EE training: http://courses.coreservlets.com

• MVC with beans, custom tags, and a framework like Struts or JSF

6

Application

Page 3: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Components That Make Up a Tag LibraryTag Library

• The Tag Handler Class– Java code that says what to output– Must implement javax.servlet.jsp.tagext.SimpleTag

Usually extends SimpleTagSupport– Usually extends SimpleTagSupport– Goes in same directories as servlet class files and beans

• The Tag Library Descriptor FileThe Tag Library Descriptor File– XML file describing tag name, attributes, and

implementing tag handler class– Goes under WEB-INF

• The JSP FileI t t lib ( f i URL f d i t fil )

Java EE training: http://courses.coreservlets.com

– Imports a tag library (referencing URL of descriptor file)– Defines tag prefix– Uses tags7

Defining a Simple Tag Handler ClassClass

• Extend the SimpleTagSupport class• Import needed packages

– import javax.servlet.jsp.*;import javax servlet jsp tagext *;import javax.servlet.jsp.tagext.*;import java.io.*;

• Override doTagg– Obtain the JspWriter with getJspContext().getOut()– Use the JspWriter to generate output– Code gets called at request time

• Tag instances are not reused like servlet instances, so no worry about race conditions, even if you have instance

Java EE training: http://courses.coreservlets.com

y yvariables

8

Page 4: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Defining a Simple Tag Handler Class: ExampleClass: Example

package coreservlets.tags;

import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import java.io.*;import java.math.*;import coreservlets.Primes;

public class SimplePrimeTag extends SimpleTagSupport {protected int length = 50;

bli id d T () th J E ti IOE ti {public void doTag() throws JspException, IOException {JspWriter out = getJspContext().getOut();BigInteger prime = Primes nextPrime(Primes random(length));

Java EE training: http://courses.coreservlets.com

Primes.nextPrime(Primes.random(length));out.print(prime);

}}9

Defining a Simple Tag Library DescriptorDescriptor

• Start with XML header• Top-level element is taglib

– Just use tlib-version and short-name as in exampleE h t d fi d b l t ith• Each tag defined by tag element with:– description, which gives short info. Optional.

name which defines the base tag name– name, which defines the base tag name. – tag-class, which gives the fully qualified class name of

the tag handler. – body-content, which specifies if tag is standalone or

contains content between start and end tag. • You can have multiple tag entries in each TLD file

Java EE training: http://courses.coreservlets.com

• You can have multiple tag entries in each TLD file• Put TLD file somewhere under WEB-INF

10

Page 5: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

TLD File for SimplePrimeTagp g

<?xml version="1.0" encoding="UTF-8" ?><taglib xmlns="http://java.sun.com/xml/ns/j2ee"

mlns si "http // 3 org/2001/XMLSchema instance"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"version="2.0"><tlib-version>1.0</tlib-version>tlib version 1.0 /tlib version<short-name>csajsp-taglib</short-name>

<tag><description>Outputs 50-digit primes</description>

i l P i /<name>simplePrime</name><tag-class>coreservlets.tags.SimplePrimeTag</tag-class><body-content>empty</body-content>

</tag>......

</taglib>

• Don't memorize XML header and standard part; download and modify online version

Java EE training: http://courses.coreservlets.com

part; download and modify online version– The important thing is to know how to write tag entries– Place TLD file somewhere under WEB-INF

11

Accessing Custom Tags From JSP FilesJSP Files

• Import the tag library– Specify location of TLD file

<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"prefix="csajsp" %>prefix csajsp %

– Define a tag prefix (namespace)<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"

fi " j " %>prefix="csajsp" %>

• Use the tags<prefix:tagName />– <prefix:tagName />

• Tag name comes from TLD file• Prefix comes from taglib directive

j i l i /

Java EE training: http://courses.coreservlets.com

– E.g., <csajsp:simplePrime />

12

Page 6: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Using simplePrime Tagg p g

...<BODY><BODY><H1>Some 50-Digit Primes</H1>

<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"<%@ taglib uri= /WEB INF/tlds/csajsp taglib.tld prefix="csajsp" %>

<UL><LI><csajsp:simplePrime />j p p<LI><csajsp:simplePrime /><LI><csajsp:simplePrime /><LI><csajsp:simplePrime />

</UL>

</BODY>

Java EE training: http://courses.coreservlets.com

</HTML>

13

Using simplePrime Tag:ResultResult

Java EE training: http://courses.coreservlets.com14

Page 7: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Assigning Attributes to Tagsg g g

• Allowing tags like– <prefix:name

attribute1="value1" attribute2="value2"attribute2 value2 ... attributeN="valueN"

/>/>

• Tags are still standalone– No body between start and end tagsNo body between start and end tags

Java EE training: http://courses.coreservlets.com15

Attributes: The Tag Handler ClassThe Tag Handler Class

• Use of an attribute called attribute1i l l i ll h d ll dsimply results in a call to a method called setAttribute1

Attribute value is supplied to method as a String– Attribute value is supplied to method as a String

• Example– To supportTo support

<prefix:tagName attribute1="Test" />

add the following to tag handler class:

bli id ib ( i l ) {

Java EE training: http://courses.coreservlets.com

public void setAttribute1(String value1) {doSomethingWith(value1);

}16

Page 8: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Attributes: PrimeTag.javag j

package coreservlets.tags;

public class PrimeTag extends SimplePrimeTag {public void setLength(String length) {try {this.length = Integer.parseInt(length);

} catch(NumberFormatException nfe) {} catch(NumberFormatException nfe) {this.length = 50;

}}

}

Java EE training: http://courses.coreservlets.com17

Attributes: The Tag Library Descriptor FileThe Tag Library Descriptor File

• The tag element must contain a nested l tattribute element

• The attribute element has three further-nested elementsnested elements– name, a required element that defines the case-sensitive

attribute name. – required, a required element that stipulates whether the

attribute must always be supplied (true) or is optional (false)(false).

– rtexprvalue, an optional attribute that indicates whether the attribute value can be a JSP expression like

Java EE training: http://courses.coreservlets.com

p<%= expression %> (true) or whether it must be a fixed string (false). The default value is false.

18

Page 9: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

TLD File for PrimeTagg

...<taglib ><taglib ...>...<tag>

<description>Outputs an N-digit prime</description><description>Outputs an N digit prime</description><name>prime</name><tag-class>coreservlets.tags.PrimeTag</tag-class><body-content>empty</body-content><body content>empty</body content><attribute>

<name>length</name><required>false</required>equ ed a se / equ ed

</attribute></tag>...

Java EE training: http://courses.coreservlets.com

</taglib>

19

Using prime Tagg p g

...<BODY><BODY><H1>Some N-Digit Primes</H1>

<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld" prefix="csajsp" %>

<UL><LI>20-digit: <csajsp:prime length="20" />

di i j i l h /<LI>40-digit: <csajsp:prime length="40" /><LI>80-digit: <csajsp:prime length="80" /><LI>Default (50-digit): <csajsp:prime />

</UL></UL>

</BODY></HTML>

Java EE training: http://courses.coreservlets.com

</HTML>

20

Page 10: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Using prime Tag: Resultg p g

Java EE training: http://courses.coreservlets.com21

Including the Tag Bodyg g y

• Simplest tags– <prefix:tagName />

• Tags with attributesfi N 1 " l1" /– <prefix:tagName att1="val1" ... />

• Now<prefix:tagName>– <prefix:tagName>Scriptless JSP Content</prefix:tagName>

– <prefix:tagName att1="val1" ... >Scriptless JSP Content

Java EE training: http://courses.coreservlets.com

Scriptless JSP Content</prefix:tagName>

22

Page 11: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Including Tag Body:The Tag Handler ClassThe Tag Handler Class

• Call getJspBody().invoke(null);g p y() ( )

public void doTag() throws ... {JspWriter out = getJspContext().getOut();out.print("...");getJspBody().invoke(null);out.print("...");p ( );

}

Java EE training: http://courses.coreservlets.com23

Including Tag Body:HeadingTag javaHeadingTag.java

public class HeadingTag extends SimpleTagSupport {private String align;private String bgColor;private String border;private String fgColor;private String font;private String font;private String size;

public void setAlign(String align) {this align = align;this.align = align;

}

public void setBgColor(String bgColor) {hi b l b lthis.bgColor = bgColor;

}

public void setBorder(String border) {

Java EE training: http://courses.coreservlets.com

this.border = border;}…

24

Page 12: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Including Tag Body:HeadingTag java (Continued)HeadingTag.java (Continued)

public void doTag() throws JspException, IOException {public void doTag() throws JspException, IOException {JspWriter out = getJspContext().getOut();out.print("<TABLE ALIGN=\"" + align + "\"\n" +

" BGCOLOR=\"" + bgColor + "\"\n" +" BORDER=" + border + "\">\n");

out.print("<TR><TH>");out.print("<SPAN STYLE=\"color: " + fgColor + ";\n" +

" font-family: " + font + ";\n" + font-family: + font + ;\n +" font-size: " + size + "px; " +"\">\n");

// Output content of the bodygetJspBody().invoke(null);out.println("</SPAN></TH></TR></TABLE>" +

"<BR CLEAR=\"ALL\"><BR>");}

Java EE training: http://courses.coreservlets.com

}}

25

Using Tag Body:The Tag Library Descriptor FileThe Tag Library Descriptor File

• Only difference is body-content elementSh ld b i l i d f– Should be scriptless instead of empty:<tag><name>…</name><tag-class> </tag-class><tag-class>…</tag-class><body-content>scriptless</body-content>

</tag>

• Legal values for body-content• Legal values for body-content– empty: no body content

• Body content is ignored even if supplied– scriptless: body content is included

• Can contain plain text, EL elements, and page directives only

Java EE training: http://courses.coreservlets.com

y• No explicit scripting allowed (<%= ... %>)

– tagdependent: body content is processed by tag26

Page 13: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

heading Tag: TLD File g g

<tag><description>Formats enclosed heading</description>p g p<name>heading</name><tag-class>coreservlets.tags.HeadingTag</tag-class><body-content>scriptless</body-content><attribute><attribute>

<name>align</name><required>true</required>

</attribute><attribute>

<name>bgColor</name><required>true</required>

</attribute></attribute> ...

</tag>

Java EE training: http://courses.coreservlets.com27

Using heading Tag g g g

…<BODY><%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld" g j p g

prefix="csajsp" %><csajsp:heading align="LEFT" bgColor="CYAN"

border="10" fgColor="BLACK" font="Arial Black" size="78">font="Arial Black" size="78">

First Heading</csajsp:heading><csajsp:heading align="RIGHT" bgColor="RED"

border="1" fgColor="YELLOW" font="Times New Roman" size="50">

Second Heading</csajsp:heading></csajsp:heading><csajsp:heading align="CENTER" bgColor="#C0C0C0"

border="20" fgColor="BLUE" font="Arial Narrow" size="100">

Java EE training: http://courses.coreservlets.com

Third Heading</csajsp:heading>

28

Page 14: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Using heading Tag:ResultsResults

Java EE training: http://courses.coreservlets.com29

Using heading Tag:More ResultsMore Results

Java EE training: http://courses.coreservlets.com30

Page 15: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Optional Tag Bodiesp g

• First examples had no tag bodies– body-content: empty– doTag does not call invoke(null)

Most recent examples always included• Most recent examples always includedtag bodies– body-content: scriptlessbody content: scriptless– doTag calls invoke(null)

• Now: decide at request time whether or not qto include tag body– body-content: scriptless

Java EE training: http://courses.coreservlets.com

– doTag conditionally calls invoke(null)• Depending on run-time information

31

Optional Tag Bodies: DebugTag javaDebugTag.java

public class DebugTag extends SimpleTagSupport {public void doTag() throws JspException, IOException {PageContext context = (PageContext)getJspContext();HttpServletRequest request =(HttpServletRequest)context getRequest();(HttpServletRequest)context.getRequest();

// Output body of tag only if debug param is present.if (request.getParameter("debug") != null) {getJspBody().invoke(null);

}}

}

Java EE training: http://courses.coreservlets.com32

Page 16: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

TLD File for DebugTagg g

...<tag><tag>

<description>Conditionally outputs enclosed body

</description></description><name>debug</name><tag-class>coreservlets.tags.DebugTag</tag-class><body-content>scriptless</body-content><body content>scriptless</body content>

</tag>...

Java EE training: http://courses.coreservlets.com33

Using debug Tagg g g

<%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld" prefix="csajsp" %>prefix= csajsp %>

Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.<csajsp:debug><csajsp:debug><H2>Debug Info:</H2>********************<BR>-Remote Host: ${pageContext.request.remoteHost}<BR>Remote Host: ${pageContext.request.remoteHost}<BR>-Session ID: ${pageContext.session.id}<BR>-The foo parameter: ${param.foo}<BR>********************<BR></csajsp:debug><P>Bottom of regular page. Blah, blah, blah.

Java EE training: http://courses.coreservlets.com

g p g , ,Yadda, yadda, yadda.

34

Page 17: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Using debug Tag: Resultsg g g

Java EE training: http://courses.coreservlets.com35

The <uri> Tag in TLD Filesg

• TLD files can define fake addresses<? ml ersion "1 0" encoding "UTF 8" ?><?xml version="1.0" encoding="UTF-8" ?><taglib ...> ...<uri>http://anything/you/want</uri>

• JSP pages import TLD using fake addressJSP pages import TLD using fake address<%@ taglib uri="http://anything/you/want" ...%>

• Note: this address is totally made up: it just matches what is in the TLD file. JSP page does not connect to the Web to look for this address.

Ad t• Advantage– Can move/rename TLD file with no JSP code changes

• You can even bundle tag libraries in JAR files under WEB-INF/lib and t TLD fil i META INF i th JAR filput TLD files in META-INF in the JAR files

– If you write JSP pages using XML syntax, you can use an additional xmlns entry to the root element and omit the @taglib declaration.

• Disadvantage

Java EE training: http://courses.coreservlets.com

• Disadvantage– Confusing: JSP authors don't know where TLD file is

36

Page 18: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Example: The <uri> Tagp g

• TLD FileI WEB INF/ ld /fil ld

• JSP (Approach 1)<%@ t lib– In WEB-INF/tlds/file.tld

<?xml ... ?><taglib ...>

<%@ taglib uri="/WEB-INF/tlds/file.tld"prefix="myPrefix" %>

...<taglib ...><uri>

http://foo.com/bar</uri>

<myPrefix:myTag/>...

JSP (A h 2)<tag>

<name>myTag</name><tag-class>...</tag-class>

• JSP (Approach 2)<%@ taglib

uri="http://foo.com/bar"prefix="myPrefix" %>

<body-content>empty or scriptless

</body-content></tag>

prefix= myPrefix %>...<myPrefix:myTag/>...

Java EE training: http://courses.coreservlets.com

</tag></taglib>

37

Tag Files: Custom Tags Using JSP SyntaxCustom Tags Using JSP Syntax

• Two Approaches– When there is lots of logic, use Java to create output

• Analagous to when you use servlets

– When there is lots of formatting use JSP to create output– When there is lots of formatting, use JSP to create output• Analagous to when you use JSP pages

• Pros– Very good for complex text formatting– Very concise

C• Cons– Not good for complicated logic

Runs only in JSP 2 0 and later

Java EE training: http://courses.coreservlets.com

– Runs only in JSP 2.0 and later• Java-based versions had "classic" syntax that worked in

older servers (e.g., BEA WebLogic 8.1, Oracle 9i AS)38

Page 19: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Simple Standalone Tagsp g

• Java-based approach requires three pieces– Java code that overrides doTag to generate output

• Strengths and weaknesses generally similar to those of servlets, but more cumbersome,

– Tag Library Descriptor (TLD) file that maps Java class name to tag nameJSP th t f t ifi l ti f TLD fil– JSP page that refers to specific location of TLD file

• JSP-based approach requires two piecesJSP code (tag file) that shows result– JSP code (tag file) that shows result

• /WEB-INF/tags/someName.tag

– No TLD file: tag name taken from tag-file name

Java EE training: http://courses.coreservlets.com

– JSP page that refers to directory containing tag file• /WEB-INF/tags or a subdirectory thereof

39

Tag Filesg

• Look just like regular JSP files, exceptM b l d i ( d ) WEB INF/– Must be located in (or under) WEB-INF/tags

– Must be named blah.tag, not blah.jsp– You use <%@ tag ... %> instead of <%@ page ... %>– You use predefined variable jspContext instead of pageContext

• But you can cast it to PageContext• Other variables (request, response, etc.) are the same

• Example

WEB-INF/tags/date.tag some-page.jsp

<%@ tag import="java.util.*" %>Date is <%= new Date() %>

<%@ taglib tagdir="/WEB-INF/tags"prefix="test" %>

Java EE training: http://courses.coreservlets.com

prefix= test %>...<test:date/>

40

Page 20: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Java-Based Tags: Code (Simple Standalone Tag)(Simple Standalone Tag)

package coreservlets.tags;

import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import java.io.*;import java.math.*;import coreservlets.Primes;

public class SimplePrimeTag extends SimpleTagSupport {protected int length = 50;

bli id d T () th J E ti IOE ti {public void doTag() throws JspException, IOException {JspWriter out = getJspContext().getOut();BigInteger prime = Primes nextPrime(Primes random(length));

Java EE training: http://courses.coreservlets.com

Primes.nextPrime(Primes.random(length));out.print(prime);

}}41

Java-Based Tags: TLD File(Simple Standalone Tag)(Simple Standalone Tag)

<?xml version="1.0" encoding="UTF-8" ?><taglib xmlns="http://java.sun.com/xml/ns/j2ee"<taglib xmlns http://java.sun.com/xml/ns/j2eexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"version="2.0"><tlib-version>1.0</tlib-version><short-name>csajsp-taglib</short-name>

<tag><description>Outputs 50-digit primes</description><name>simplePrime</name><tag-class>coreservlets.tags.SimplePrimeTag</tag-class><body-content>empty</body-content>

</tag>

Java EE training: http://courses.coreservlets.com

...</taglib>

42

Page 21: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Java-Based Tags: Usage in JSP(Simple Standalone Tag)(Simple Standalone Tag)...<BODY><BODY><H1>Some 50-Digit Primes</H1><%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"

prefix="csajsp" %><UL><LI><csajsp:simplePrime /><LI><csajsp:simplePrime /><LI><csajsp:simplePrime /><LI><csajsp:simplePrime /><LI>< j i l P i /><LI><csajsp:simplePrime />

</UL></BODY></HTML>

Java EE training: http://courses.coreservlets.com43

Java-Based Tags: Result(Simple Standalone Tag)(Simple Standalone Tag)

Java EE training: http://courses.coreservlets.com44

Page 22: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Tag Files: Tag Code(Simple Standalone Tag)(Simple Standalone Tag)

• WEB-INF/tags/simplePrime2.tag– Directory name is not arbitrary; must be in

/WEB-INF/tags or a subdirectory thereof

<%= coreservlets.Primes.nextPrime(coreservlets.Primes.random(50)) %>

Java EE training: http://courses.coreservlets.com45

Tag Files: Usage in JSP(Simple Standalone Tag)(Simple Standalone Tag)...<BODY><BODY><H1>Some 50-Digit Primes</H1>

<%@ taglib tagdir="/WEB-INF/tags"<%@ taglib tagdir /WEB INF/tagsprefix="csajsp" %>

<UL><LI><csajsp:simplePrime2 />j p p<LI><csajsp:simplePrime2 /><LI><csajsp:simplePrime2 /><LI><csajsp:simplePrime2 />

</UL></BODY></HTML>

Java EE training: http://courses.coreservlets.com46

Page 23: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Tag Files: Result(Simple Standalone Tag)(Simple Standalone Tag)

Java EE training: http://courses.coreservlets.com47

Tags with Attributesg

• Java-based tags– For each attribute, add setAttributeName method to the

Java class– Attribute value usually explicitly stored in instance– Attribute value usually explicitly stored in instance

variable (field) of Java class– List each attribute explicitly in TLD file

• JSP-based tags (tag files)– Each attribute listed in tag file with @attribute

C l li t i d d t l (d f lt f l )• Can also list required and rtexprvalue (default false)

– Attribute value automatically stored in scoped variable (for access from expression language) and in local

Java EE training: http://courses.coreservlets.com

( p g g )variable (for access from Java code)

– No TLD file48

Page 24: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Java-Based Tags: Code(Tag with Attributes)(Tag with Attributes)package coreservlets.tags;

public class PrimeTag extends SimplePrimeTag {public void setLength(String length) {

try {try {this.length = Integer.parseInt(length);

} catch(NumberFormatException nfe) {thi l th 50this.length = 50;

}}

}

Java EE training: http://courses.coreservlets.com49

Java-Based Tags: TLD File(Tag with Attributes)(Tag with Attributes)

…<tag><tag>

<description>Outputs an N-digit prime</description><name>prime</name><tag-class>coreservlets.tags.PrimeTag</tag-class><tag class>coreservlets.tags.PrimeTag</tag class><body-content>empty</body-content><attribute>

<name>length</name><name>length</name><required>false</required>

</attribute></tag>/tag

Java EE training: http://courses.coreservlets.com50

Page 25: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Java-Based Tags: Usage in JSP(Tag with Attributes)(Tag with Attributes)…<BODY><BODY><H1>Some N-Digit Primes</H1><%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"

prefix="csajsp" %><UL>

<LI>20-digit: <csajsp:prime length="20" /><LI>40-digit: <csajsp:prime length="40" /><LI>80-digit: <csajsp:prime length="80" /><LI>Default (50-digit): <csajsp:prime />( g ) j p p /

</UL></BODY></HTML>

Java EE training: http://courses.coreservlets.com51

Java-Based Tags: Results(Tag with Attributes)(Tag with Attributes)

Java EE training: http://courses.coreservlets.com52

Page 26: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Tag Files: Tag Code(Tag with Attributes)(Tag with Attributes)<%@ attribute name="length" required="false" %><%<% int len = 50;try {len = Integer.parseInt(length);

} catch(NumberFormatException nfe) {}%>%><%= coreservlets.Primes.nextPrime

(coreservlets.Primes.random(len)) %>

Java EE training: http://courses.coreservlets.com53

Tag Files: Usage in JSP(Tag with Attributes)(Tag with Attributes)…<BODY><BODY><H1>Some N-Digit Primes</H1><%@ taglib tagdir="/WEB-INF/tags"

prefix="csajsp" %><UL>

<LI>20-digit: <csajsp:prime2 length="20" /><LI>40-digit: <csajsp:prime2 length="40" /><LI>80-digit: <csajsp:prime2 length="80" /><LI>Default (50-digit): <csajsp:prime2 />( g ) j p p /

</UL></BODY></HTML>

Java EE training: http://courses.coreservlets.com54

Page 27: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Tag Files: Results(Tag with Attributes)(Tag with Attributes)

Java EE training: http://courses.coreservlets.com55

Tags with Bodiesg

• Java-based tags– Change body-content from empty to scriptless (in TLD)– Call getJspBody().invoke(null)

Still need setter method and TLD entry for every attribute– Still need setter method and TLD entry for every attribute

• JSP-based tags (tag files)JSP based tags (tag files)– Use <jsp:doBody/> to output tag body– No major syntax changes– Access to attributes still much simpler

Java EE training: http://courses.coreservlets.com56

Page 28: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Java-Based Tags: Code (Tag with Body)(Tag with Body)

public class HeadingTag extends SimpleTagSupport {private String align;private String bgColor;private String border;private String fgColor;private String font;private String font;private String size;

public void setAlign(String align) {this align = align;this.align = align;

}

public void setBgColor(String bgColor) {hi b l b lthis.bgColor = bgColor;

}

public void setBorder(String border) {

Java EE training: http://courses.coreservlets.com

this.border = border;}…

57

Java-Based Tags: Code (Tag with Body -- Continued)(Tag with Body -- Continued)

public void doTag() throws JspException, IOException {public void doTag() throws JspException, IOException {JspWriter out = getJspContext().getOut();out.print("<TABLE ALIGN=\"" + align + "\"\n" +

" BGCOLOR=\"" + bgColor + "\"\n" +" BORDER=" + border + "\">\n");

out.print("<TR><TH>");out.print("<SPAN STYLE=\"color: " + fgColor + ";\n" +

" font-family: " + font + ";\n" + font-family: + font + ;\n +" font-size: " + size + "px; " +"\">\n"); //

// Output content of the bodygetJspBody().invoke(null);out.println("</SPAN></TH></TR></TABLE>" +

"<BR CLEAR=\"ALL\"><BR>");}

Java EE training: http://courses.coreservlets.com

}}

58

Page 29: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Java-Based Tags: TLD File (Tag with Body)(Tag with Body)

...<tag>g

<description>Formats enclosed heading</description><name>heading</name><tag-class>coreservlets.tags.HeadingTag</tag-class><body content>scriptless</body content><body-content>scriptless</body-content><attribute>

<name>align</name><required>true</required>

</attribute><attribute>

<name>bgColor</name><required>true</required><required>true</required>

</attribute> ...

</tag>

Java EE training: http://courses.coreservlets.com59

Java-Based Tags: Usage in JSP (Tag with Body)(Tag with Body)

<BODY><%@ taglib uri="/WEB-INF/tlds/csajsp-taglib.tld"g j p g

prefix="csajsp" %><csajsp:heading align="LEFT" bgColor="CYAN"

border="10" fgColor="BLACK" font="Arial Black" size="78">font="Arial Black" size="78">

First Heading</csajsp:heading><csajsp:heading align="RIGHT" bgColor="RED"

border="1" fgColor="YELLOW" font="Times New Roman" size="50">

Second Heading</csajsp:heading></csajsp:heading><csajsp:heading align="CENTER" bgColor="#C0C0C0"

border="20" fgColor="BLUE" font="Arial Narrow" size="100">

Java EE training: http://courses.coreservlets.com

Third Heading</csajsp:heading>

60

Page 30: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Java-Based Tags: Results (Tag with Body)(Tag with Body)

Java EE training: http://courses.coreservlets.com61

Tag Files: Tag Code (Tag with Body)(Tag with Body)<%@ attribute name="align" required="true" %><%@ attribute name="bgColor" required="true" %><%@ attribute name="bgColor" required="true" %><%@ attribute name="border" required="true" %><%@ attribute name="fgColor" required="true" %><%@ attribute name "font" required "true" %><%@ attribute name="font" required="true" %><%@ attribute name="size" required="true" %><TABLE ALIGN="${align}"

BGCOLOR "${b C l }"BGCOLOR="${bgColor}"BORDER="${border}">

<TR><TH>$<SPAN STYLE="color: ${fgColor};

font-family: ${font};font-size: ${size}px;">

Java EE training: http://courses.coreservlets.com

<jsp:doBody/></SPAN></TABLE><BR CLEAR="ALL"><BR>

62

Page 31: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Tag Files: Usage in JSP (Tag with Body)(Tag with Body)

<BODY><%@ taglib tagdir="/WEB-INF/tags"g g g

prefix="csajsp" %><csajsp:heading2 align="LEFT" bgColor="CYAN"

border="10" fgColor="BLACK" font="Arial Black" size="78">font="Arial Black" size="78">

First Heading</csajsp:heading2><csajsp:heading2 align="RIGHT" bgColor="RED"

border="1" fgColor="YELLOW" font="Times New Roman" size="50">

Second Heading</csajsp:heading2></csajsp:heading2><csajsp:heading2 align="CENTER" bgColor="#C0C0C0"

border="20" fgColor="BLUE" font="Arial Narrow" size="100">

Java EE training: http://courses.coreservlets.com

Third Heading</csajsp:heading2>

63

Tag Files: Results (Tag with Body)(Tag with Body)

Java EE training: http://courses.coreservlets.com64

Page 32: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Open Source Tag Librariesp g

• JSP Standard Tag Library (JSTL)C d i l t l t– Covered in later lecture

• AjaxTags– http://ajaxtags.sourceforge.net/p j g g

• Jakarta Taglibs– http://jakarta.apache.org/taglibs/

• Benchmarking• Benchmarking• Internationalization (I18N)• Database access• Sending emailSe d g e a• Populating/validating form fields• Regular expressions• Extracting data from other Web pages

Java EE training: http://courses.coreservlets.com

• Logging• Etc.

65

Summary: Java-Based Tagsy g

• Tag handler classExtend SimpleTagSupport– Extend SimpleTagSupport

– Override doTag– Get the JspWriter with getJspContext().getOut()

Use the JspWriter to generate output– Use the JspWriter to generate output– Output tag body with getJspBody().invoke(null);– Define setBlah for each attribute named blah

• TLD File (/WEB-INF/ /somefile tld)• TLD File (/WEB-INF/.../somefile.tld)– <tag> ... </tag>

• Contains description (optional), name, tag-class, body-content, attribute (one for each attribute)

– <uri>http://fake-address</uri> (optional)• JSP File

– <%@ taglib uri="/WEB-INF/.../somefile.tld" prefix="blah" %>

Java EE training: http://courses.coreservlets.com

@ g p• Or <%@ taglib uri="http://fake-address" prefix="blah" %>

– <blah:tagName/> or <blah:tagName>...</blah:tagName>66

Page 33: Creating Custom JSP TagCreating Custom JSP Tag Libraries ...courses.coreservlets.com/Course-Materials/pdf/ajax/Custom-Tags-B… · • Java-based tags – Components of a tag library

Summary: Tag Filesy g

• Tag File– /WEB-INF/tags/tagName.tag– Create chunk of JSP that generates the output

Declare attributes with <%@ attribute %>– Declare attributes with <%@ attribute ...%>– Output attributes with ${attributeName}– Output the tag body with <jsp:doBody/>p g y j p y– Refactor Java code so methods take strings as args

• JSP File– <%@ taglib tagdir="/WEB-INF/tags prefix="blah" %>– <blah:tagName/> or <blah:tagName>...</blah:tagName>

Java EE training: http://courses.coreservlets.com67

© 2008 Marty Hall

Questions?Questions?

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.68