30
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags 4.1.0 .3

JSP Custom Tags

  • Upload
    yadid

  • View
    64

  • Download
    0

Embed Size (px)

DESCRIPTION

JSP Custom Tags. 4.1.0.3. Unit objectives. After completing this unit, you should be able to: Describe the advantages of using JSP custom tags List the major steps in developing and using JSP custom tags Develop basic tag handler classes to implement JSP custom tags - PowerPoint PPT Presentation

Citation preview

Page 1: JSP Custom Tags

®

IBM Software Group

© 2007 IBM Corporation

JSP Custom Tags

4.1.0.3

Page 2: JSP Custom Tags

2

After completing this unit, you should be able to: Describe the advantages of using JSP custom tags List the major steps in developing and using JSP custom tags Develop basic tag handler classes to implement JSP custom

tags Create and modify taglib descriptor files Package JSP taglib implementation classes and taglib

descriptor files Understand the uses of the JSTL Name some of the tags included in the JSTL and their

purposes

Unit objectives

Page 3: JSP Custom Tags

3

JSP Custom Tags Overview Nine standard actions must be provided by any compliant JSP

implementation:useBean, setProperty, getPropertyinclude, forwardplug-in, params, param, fallback

Custom tags allow developers to create additional actions beyond the standard set

Custom actions are invoked via custom tags in a JSP page Tag libraries are collections of custom tags Support for JSP custom tags is required by the JSP

specification

<jsp:useBean id="customer" class="com.ibm.model.customer" /><jsp:setProperty name="customer" property="id" value="0" /><jsp:include page=“banner.jsp” />

Page 4: JSP Custom Tags

4

Why Use JSP Custom Tags? Role-based development

Model classes (business objects and data storage layers) are developed by Java and EJB developers

Controller classes (servlets) are developed by Java developers

View-based JSP pages are developed by HTML developers Different roles:

Use different toolsHave different skills

Best PracticeMVC design is well establishedUse the right tools for the right jobs

Page 5: JSP Custom Tags

5

Steps to Create and Use a Custom Tag Library To develop a tag, you need to:

Design your tags and attributesDeclare the tag in a tag library descriptor (TLD)Develop a tag handler classDevelop helper classes for the tag (if needed)

To use a custom tag, the JSP needs to:Include the tag library using the taglib directiveCode the custom tag with any needed attributesTest your tags

class 1

class 2

helperclass

TLDJSPPage

Page 6: JSP Custom Tags

6

Tag Usage Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 transitional//EN">

<HTML><HEAD><%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix=“tl" %><%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1“%><TITLE>Date Demo</TITLE></HEAD><BODY><h1>Date Demo</h1><P>Fully formatted date:<tl:date format=”full”/></P></BODY></HTML>

Page 7: JSP Custom Tags

7

JSP Page Without Custom Tags

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML><HEAD><%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><TITLE>Date Demo</TITLE></HEAD><BODY><h1>Date Demo</h1><P>Fully formatted date:<% java.util.Locale locale = pageContext.getRequest().getLocale(); java.text.DateFormat fmt = java.text.DateFormat.getDateInstance (java.text.DateFormat.FULL,locale); String date = fmt.format(new java.util.Date()); %><%= date %></P></BODY></HTML>

Page 8: JSP Custom Tags

8

Using Custom Tags with Application Developer Page Designer has different ways of selecting a tag for

inclusion with JSP 1. Select JSP->Insert Custom 2. Drag Custom from JSP Tags drawer in Palette

Select desired tag from Insert Custom Tag dialog

1

2

Page 9: JSP Custom Tags

9

JSP Standard Tag Library (JSTL) Encapsulates as tags core functionality of many Web applications Supports tasks such as:

Flow (iteration and conditionals)Manipulation of XML documentsInternationalization tagsSQL tags

J2EE 1.4 includes both JSP and JSTLJSTL taglibs included with Rational Application Developer

Page 10: JSP Custom Tags

10

Sample JSTL Tags Set a variable in a specific scope to a value

<c:set var="name" scope="scope" value="expression"/> Display a value, or an alternative if the first value is null

<c:out value="expr" default="expr" escapeXml="boolean"/> Example:

Hello <c:out value="${user.name}" default="Guest"/>! Conditional execution

<c:choose>, <c:when> and <c:otherwise><c:choose> <c:when test="${user.role == 'member'}"> <p>Welcome, member!</p> </c:when> <c:otherwise> <p>Welcome, guest!</p> </c:otherwise></c:choose>

Page 11: JSP Custom Tags

11

forEach Tag Provides flexible iteration through a set of items Targets include:

Collections, Maps, Iterators, EnumerationsArraysComma-separated valuesSQL ResultSets

Example:<table> <c:forEach items="${customers}" var=“cust"> <tr> <td>${cust.name}</td> <td>${cust.addr}</td> </tr> </c:forEach></table>

Page 12: JSP Custom Tags

12

Anatomy of a Tag

<tl:asis tab="5">Instructions for logging in to the system: (1)Enter your Patron identifier in ID field (2)Enter assigned password in PW field (3)Click on LOGIN button </tl:asis>

Start tag

Body(optional)

End tag

Attribute (optional)Element

Page 13: JSP Custom Tags

13

Tag Examples Basic<tl:fullText />

With attributes<tl:code language="java“/>

With attributes and a body<tl:iterator times=10>

<p>"Hello world."</p></tl:iterator>

Defining scripting variables<tl:iterator name="list" id="customer” type="domain.Customer"> <jsp:getProperty name="customer" property="name" /></tl:iterator>

Page 14: JSP Custom Tags

14

Describing Tags to the JSP Container Done with the taglib descriptor (TLD)

XML fileDescribes the tag libraryFiles use the .tld extension

Defines the syntax of the tags (actions) Defines the attributes (if any) for the tags

Specifies if the attribute is optional or required Specifies the Java class that implements the tag Specifies if the tag allows or uses a body Used by the JSP container to validate the JSP at compile time

Page 15: JSP Custom Tags

15

General Format of the TLD (1 of 2)

Defines the date tag

<?xml version="1.0" encoding="UTF-8"?><taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">

<tag> <name>date</name> <tag-class>com.ibm.library.tag.FormattedDate</tag-class> <body-content>empty</body-content> <description>Display current date</description> </tag>

<description>Tag Library from IBM Library System </description> <tlib-version>1.0</tlib-version> <short-name>ilib</short-name>

Required

Info about TLD

Tag Info

Page 16: JSP Custom Tags

16

General Format of the TLD (2 of 2)

<tag> <name>date2</name>

<tag-class>com.ibm.library.tag.FormatDate2</tag-class>

<body-content>JSP</body-content>

</tag></taglib>

<attribute>

<name>format</name> <required>true</required>

</attribute>

Action name

Tag handler class implementation

How to process the body

Attribute name (multiple allowed)

Optional (false) or mandatory (true)

Page 17: JSP Custom Tags

17

Location of TLD File Resides in the META-INF directory or subdirectory when

deployed inside a JAR file Resides in the WEB-INF directory or some subdirectory when

deployed directly into a Web application

XML Schema is located at URL:http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd

Page 18: JSP Custom Tags

18

JSP Taglib Directive Taglib directive tells your JSP the prefix to be used for a

specific JSP tag library

<!DOCTYPE … ><HTML><HEAD><%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix="tl" %>…<TITLE>date test</TITLE></HEAD><BODY>…<tl:date format="full"/>…</BODY></HTML>

Taglib directive

Taglib usage

Location of TLD

Prefix for this JSP

Page 19: JSP Custom Tags

19

Tag Handler Base Classes Tag handlers must implement specific

interfaces or extend specific classes, and must override key methods

These classes all reside in javax.servlet.jsp.tagext

JSP 2.0 introduced SimpleTag “classic

” tags

Page 20: JSP Custom Tags

20

Example Tag The <transform> tag allows page developers to transform the

contained text in two ways:Convert it to upper caseHide it

The tag has a required attribute mode with the following values:upperhide

The value of the attribute can be taken from a runtime expression

<m:transform mode="upper"><P>This is text to be transformed.</P></m:transform>

Page 21: JSP Custom Tags

21

Processing Tags with Attributes: How It Works

<m:transform mode="upper"><P>This is text to be

transformed.</P></m:transform>

1) Initialize and set attributes (setMode()) 2) Call doTag() method

Page 22: JSP Custom Tags

22

What Needs to Be Done? Create the TransformTag class Update the TLD for the new date tag Use the new <transform> tag in your JSPs

handlerclass

TLDJSPPage

Page 23: JSP Custom Tags

23

The TransformTag Class

package com.ibm.library.tag;

import java.io.IOException;import java.io.StringWriter;import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.JspFragment;import javax.servlet.jsp.tagext.SimpleTagSupport;

public class TransformTag extends SimpleTagSupport {

String mode = "";

public void setMode(String mode) { this.mode = mode.toUpperCase(); }

// class continues on next page

Page 24: JSP Custom Tags

24

The doTag() Method

public void doTag() throws JspException, IOException {

JspFragment body = getJspBody(); StringWriter oldbody = new StringWriter(); String newbody = null;

body.invoke(oldbody);

if (mode.equals("UPPER")) { newbody = oldbody.toString().toUpperCase(); } else if (mode.equals("HIDE")) { newbody = ""; } else { newbody = oldbody.toString(); }

JspWriter out = getJspContext().getOut(); out.write(newbody);}

Page 25: JSP Custom Tags

25

The Taglib Descriptor

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

<description>Tag Library for Library System</description> <tlib-version>1.0</tlib-version> <short-name>ilib</short-name> <tag> <name>transform</name> <tag-class>com.ibm.library.tag.TransformTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>mode</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag></taglib>

Page 26: JSP Custom Tags

26

Using the <transform> Tag

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><%@ taglib uri="WEB-INF/tld/mytags.tld" prefix="m" %><TITLE>transformDemo.jsp</TITLE></HEAD><BODY><H1>Demonstrate &lt;transform&gt; tag</H1><m:transform mode="UPPER"><P>This is text to be transformed</P></m:transform><P>This text is not to be transformed</P></BODY></HTML>

Page 27: JSP Custom Tags

27

Packaging To facilitate reuse, the tag handler classes can be packaged

togetherPlace the class files in a JARImport the TLD into /WEB-INF/tldImport the JAR into /WEB-INF/lib

An additional option is to package the TLD with the class files JAR

Application Developer providessupport for JSP tag library resource referencesWeb Deployment Descriptor editor

Variables tabAllows URI to be specified to reference the TLD

Page 28: JSP Custom Tags

28

Checkpoint1. What are some of the advantages of JSP custom tags?2. What are the major steps that must be performed during JSP

custom tag development?3. How are attributes’ values processed in a tag handler class?4. What method of the SimpleTag interface does the main work

of processing a tag?5. What is the purpose of the JSP taglib directive?

Page 29: JSP Custom Tags

29

Checkpoint solutions

1. Advantages of custom tags include:2. Make JSPs easier to develop, test, and maintain3. Web developer can focus on presentation (role-based

developmental4. Presentation logic is reusable5. The major steps in JSP custom tag development are:6. Design tags and attributes7. Write tag handler class8. Construct or modify TLD9. Test in a JSP10.Attribute values are processed in a tag handler class through

JavaBean-like setter methods.11.doTag() 12.The taglib directive describes the location of the TLD and

designates the tag prefix.

Page 30: JSP Custom Tags

30

Having completed this unit, you should be able to: Describe the advantages of using JSP custom tags List the major steps in developing and using JSP custom tags Develop basic tag handler classes to implement JSP custom

tags Create and modify taglib descriptor files Package JSP taglib implementation classes and taglib

descriptor files Understand the uses of the JSTL Name some of the tags included in the JSTL and their

purposes

Unit summary