Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
® IBM Software Group JSP Custom Tags © 2007 IBM Corporation 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 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 2 JSP Custom Tags Overview Nine standard actions must be provided by any compliant JSP implementation: useBean, setProperty, getProperty include, forward plug-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” /> 3 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 tools Have different skills Best Practice MVC design is well established Use the right tools for the right jobs 4 Steps to Create and Use a Custom Tag Library To develop a tag, you need to: Design your tags and attributes Declare the tag in a tag library descriptor (TLD) Develop a tag handler class Develop helper classes for the tag (if needed) To use a custom tag, the JSP needs to: Include the tag library using the taglib directive Code the custom tag with any needed attributes Test your tags class 1 JSP Page TLD class 2 5 helper class 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> 6 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> 7 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 8 2 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 documents Internationalization tags SQL tags J2EE 1.4 includes both JSP and JSTL JSTL taglibs included with Rational Application Developer 9 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> 10 forEach Tag Provides flexible iteration through a set of items Targets include: Collections, Maps, Iterators, Enumerations Arrays Comma-separated values SQL ResultSets Example: <table> <c:forEach items="${customers}" var=“cust"> <tr> <td>${cust.name}</td> <td>${cust.addr}</td> </tr> </c:forEach> </table> 11 Anatomy of a Tag Element Attribute (optional) Start tag Body (optional) End 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> 12 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> 13 Describing Tags to the JSP Container Done with the taglib descriptor (TLD) XML file Describes the tag library Files 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 14 General Format of the TLD (1 of 2) <?xml version="1.0" encoding="UTF-8"?> Required <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/webjsptaglibrary_2_0.xsd"> <description>Tag Library from IBM Library System Info about TLD </description> <tlib-version>1.0</tlib-version> <short-name>ilib</short-name> <tag> Tag Info Defines the date tag <name>date</name> <tag-class>com.ibm.library.tag.FormattedDate</tag-class> <body-content>empty</body-content> <description>Display current date</description> </tag> 15 General Format of the TLD (2 of 2) <tag> <name>date2</name> Action name Tag handler class implementation <tag-class>com.ibm.library.tag.FormatDate2</tag-class> <body-content>JSP</body-content> How to process the body <attribute> Attribute name (multiple allowed) <name>format</name> <required>true</required> </attribute> </tag> </taglib> Optional (false) or mandatory (true) 16 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 17 JSP Taglib Directive Taglib directive tells your JSP the prefix to be used for a specific JSP tag library Taglib directive Location of TLD <!DOCTYPE … > <HTML> <HEAD> <%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix="tl" %> … <TITLE>date test</TITLE> </HEAD> Prefix for this JSP <BODY> … <tl:date format="full"/> … </BODY> </HTML> Taglib usage 18 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 19 “classic” tags Example Tag The <transform> tag allows page developers to transform the contained text in two ways: Convert it to upper case Hide it The tag has a required attribute mode with the following values: upper hide 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> 20 Processing Tags with Attributes: How It Works 1) Initialize and set attributes (setMode()) 2) Call doTag() method <m:transform mode="upper"> <P>This is text to be transformed.</P> </m:transform> 21 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 JSP Page TLD 22 handler class The TransformTag Class package com.ibm.library.tag; import import import import import import java.io.IOException; java.io.StringWriter; javax.servlet.jsp.JspException; javax.servlet.jsp.JspWriter; javax.servlet.jsp.tagext.JspFragment; 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 23 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); } 24 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> 25 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 <transform> 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> 26 Packaging To facilitate reuse, the tag handler classes can be packaged together Place the class files in a JAR Import the TLD into /WEB-INF/tld Import the JAR into /WEB-INF/lib An additional option is to package the TLD with the class files JAR Application Developer provides support for JSP tag library resource references Web Deployment Descriptor editor Variables tab Allows URI to be specified to reference the TLD 27 Checkpoint 1. 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? 28 Checkpoint solutions 1. Advantages of custom tags include: 2. Make JSPs easier to develop, test, and maintain 3. Web developer can focus on presentation (role-based developmental 4. Presentation logic is reusable 5. The major steps in JSP custom tag development are: 6. Design tags and attributes 7. Write tag handler class 8. Construct or modify TLD 9. Test in a JSP 10. 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. 29 Unit summary 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 30