JSP Custom Tags
410 likes | 817 Views
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
JSP Custom Tags
E N D
Presentation Transcript
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 • 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
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” />
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
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 helper class JSP Page TLD class 2
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>
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>
1 2 Using Custom Tags with Application Developer • Page Designer has different ways of selecting a tag for inclusion with JSP • Select JSP->Insert Custom • Drag Custom from JSP Tags drawer in Palette • Select desired tag from Insert Custom Tag dialog
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
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>
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>
Anatomy of a Tag Element Attribute (optional) Start 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> Body (optional) End tag
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>
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
General Format of the TLD (1 of 2) <?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"> Required <description>Tag Library from IBM Library System </description> <tlib-version>1.0</tlib-version> <short-name>ilib</short-name> Info about TLD <tag> <name>date</name> <tag-class>com.ibm.library.tag.FormattedDate</tag-class> <body-content>empty</body-content> <description>Display current date</description> </tag> Tag Info Defines the date tag
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> Action name Tag handler class implementation How to process the body <attribute> <name>format</name> <required>true</required> </attribute> Attribute name (multiple allowed) Optional (false) or mandatory (true)
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
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> <BODY> … <tl:date format="full"/> … </BODY> </HTML> Prefix for this JSP Taglib usage
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
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>
Processing Tags with Attributes: How It Works • Initialize and set attributes (setMode()) 2) Call doTag() method <m:transform mode="upper"> <P>This is text to be transformed.</P> </m:transform>
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 handler class
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
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); }
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>
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>
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 providessupport for JSP tag library resource references • Web Deployment Descriptor editor • Variables tab • Allows URI to be specified to reference the TLD
Checkpoint • What are some of the advantages of JSP custom tags? • What are the major steps that must be performed during JSP custom tag development? • How are attributes’ values processed in a tag handler class? • What method of the SimpleTag interface does the main work of processing a tag? • What is the purpose of the JSP taglib directive?
Checkpoint solutions • Advantages of custom tags include: • Make JSPs easier to develop, test, and maintain • Web developer can focus on presentation (role-based developmental • Presentation logic is reusable • The major steps in JSP custom tag development are: • Design tags and attributes • Write tag handler class • Construct or modify TLD • Test in a JSP • Attribute values are processed in a tag handler class through JavaBean-like setter methods. • doTag() • The taglib directive describes the location of the TLD and designates the tag prefix.
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