9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags
Mar 27, 2015
9-2 Copyright © 2005, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do the following:
• Define a custom tag
• Use custom tags in a JavaServer Page (JSP)
• Use the customizable Component Palette for JSP
• Develop a JSP using the JSP Standard Tag Library (JSTL)
9-3 Copyright © 2005, Oracle. All rights reserved.
Custom Tags
• Custom tags are developed in Java and defined and used with XML syntax.
• Tags are used in a JSP to reduce or constrain the amount of Java scriptlets in the page.
• Tags are useful for defining custom actions such as:– Accessing a database– Defining recurring tasks– Sending e-mail
• Collections of tags are grouped into JAR files called Tag Libraries.
9-4 Copyright © 2005, Oracle. All rights reserved.
Custom Tag Library Components
Custom Tag Libraries contain:
• One or more tag handler class files– May contain additional supporting classes
• A tag library descriptor (taglib.tld)– XML formatted
To use a tag in a JSP, perform the following:
1. Invoke the tag library by using the <jsp:taglib/> directive.
2. Call the tag in the content of the JSP.
3. Include the location of the taglib.tld file in the web.xml file.
9-5 Copyright © 2005, Oracle. All rights reserved.
Tag Handler: Example
import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import java.io.*;public class HelloWorldTag extends TagSupport {public int doStartTag() {try { JspWriter out = pageContext.getOut(); out.print("Hello from Custom Tag!!!"); } catch(IOException io) { System.out.println("Error in TagMessage: " + io); } return(SKIP_BODY); } public int doEndTag() { return (SKIP_PAGE); }}
9-6 Copyright © 2005, Oracle. All rights reserved.
Tag Library Descriptors
A tag library descriptor (.tld) is an XML document that describes one or more tags and their attributes. It contains the following elements:
Specifies the class for the individual tag<tagclass>
Set to empty, tagdependent, or JSP<bodycontent>
Documentation regarding the library <info>
Identifies the tag library location<uri>
A default name for the library<shortname>
The JSP specification version for the library<jspversion>
The tag library’s version<tlibversion>
9-7 Copyright © 2005, Oracle. All rights reserved.
Using a Custom Tag
<html><head><%@ taglib uri="webapp/taglib.tld" prefix="mytags" %></head><body><h2>The following output is from the HelloWorldTag:</h2><p><mytags:hellotag/></p></body></html>
9-8 Copyright © 2005, Oracle. All rights reserved.
Tags with Attributes
Tags with attributes should include the get() and set() methods for each attribute in the tag handler.
• The tag library descriptor defines each attribute.
• Supporting classes can validate attributes.
<tag> <name>hellotag</name> <tagclass>HelloWorldTag</tagclass> <bodycontent>empty</bodycontent> <attribute>
<name>custName</name> <required> true</required> <rtexprvalue>true</rtexprvalue>
</attribute> </tag>
9-9 Copyright © 2005, Oracle. All rights reserved.
Creating a Custom Tag in JDeveloper
To create a custom tag and a tag library in JDeveloper, perform the following:
1. Create a tag library descriptor from the JavaServer Pages category.
2. Right-click the .tld file in System Navigator and select “Add Tag” to create a tag handler.
3. Right-click the .java file in System Navigator and select “Add Attribute” or “Add Scripting Variable” as necessary.
4. Add the tag library to the component palette.
9-10 Copyright © 2005, Oracle. All rights reserved.
Tag Libraries in JDeveloper
• Tag libraries are viewed in JDeveloper by using the component palette.
• Select View > Component Palette to enable the palette in the integrated development environment (IDE).
9-11 Copyright © 2005, Oracle. All rights reserved.
Registering Tag Libraries
To add a tag library to the component palette, perform the following:
1. Select Tools > Configure Palette.
2. Add a new palette page.
3. Name the page for display.
9-12 Copyright © 2005, Oracle. All rights reserved.
Registering Tag Libraries
4. Select Tools > Manage Libraries.
5. Add the JAR and TLD files to the list of JSP Tag Libraries.
9-15 Copyright © 2005, Oracle. All rights reserved.
JSP Standard Tag Library (JSTL)
The JSP Standard Tag Library (JSTL) was developed under the Java Community Process. It provides a common and standard set of custom tags for:
• Iteration, conditional processing, and expression language support
• Parsing and transforming XML documents
• Formatting and parsing strings, dates, and currencies for internationalization
• Database access and data manipulation
9-16 Copyright © 2005, Oracle. All rights reserved.
Core Tag Library
The Core library of JSTL is used for typical JSP actions.
• Reduces the need for scriptlet tags in a JSP
• Contains four types of tags:– Generic (sets variables and display results of
expressions)– Conditional (makes blocks of code dependent on
some criteria)– Iteration (repeats actions on blocks of code)– URL-related (creates URLs for linking or
redirection)
Use the prefix "c" in the taglib directive:<%@ taglib uri="http://java.sun.com/jstl/core"
prefix="c" %>
9-18 Copyright © 2005, Oracle. All rights reserved.
Utilizing Core Tags
• Use the <c:out> and <c:set> tags within your JSP to display and create variables. The value attribute defines what will be displayed or created as a variable:
• The value attribute of the <c:set> tag uses Expression Language (EL).
<c:out value="Hello World" /><c:set var="name" value="${param.username}" scope="session" />Welcome <c:out value="${name}" default="guest" />
9-19 Copyright © 2005, Oracle. All rights reserved.
Expression Language
JSTL tags can contain Expression Language (EL) within attributes. Expression Language:
• Is a simpler way of writing an expression in JSPs
• Accesses object properties and collection elements using dot notation
• Has access to implicit objects
• Uses a dollar sign and braces to create an expression: ${expression}
<c:set var="name" value="${param.username}" scope="session" />Welcome <c:out value="${name}" default="guest" />
9-20 Copyright © 2005, Oracle. All rights reserved.
Using Iteration Tags
Use iteration tags to iterate over blocks of code:
<table><tr> <c:forEach var="allparams" items="${param}" > <c:out value="${allparams.key}" /> </c:forEach><tr><table>
9-21 Copyright © 2005, Oracle. All rights reserved.
Using the URL Tags
The following three tags exist for working with URLs:
• <c:import>: Accesses resources by specifying a URL. It is preferred over the <jsp:include> directive, because <c:import> can:– Access URLs that exist outside the same context as
the current page’s Web application context – Access a relative URL with a foreign Web
application context– Include FTP resources
• <c:url>: Handles encoding and rewriting of URLs
• <c:redirect>: Redirects the client request
9-23 Copyright © 2005, Oracle. All rights reserved.
XML Tag Library
The XML tag library is used to parse and transform XML documents.
• XML tags in JSTL conform to XPath syntax.
• XML tags include <x:out>, <x:set>, and other tags similar to the core tag library, in addition to:– <x:parse> : Parses a specified XML document– <x:transform> : Creates a formatted page from an
XML source document by using an XSLT stylesheet– <x:param> : Sets transformation parameters
(nested in <x:transform>)
Use the prefix "x" in the taglib directive:<%@ taglib uri="http://java.sun.com/jstl/xml"
prefix="x" %>
9-24 Copyright © 2005, Oracle. All rights reserved.
SQL Tag Library
The SQL Tag Library contains tags for testing database applications.
• Only used for prototyping or low-volume applications
Use the prefix “sql” in the taglib directive:
<%@ taglib uri=http://java.sun.com/jstl/sql prefix="sql" %>
9-25 Copyright © 2005, Oracle. All rights reserved.
Accessing a Database with SQL Tags
To access a database from the SQL tags, you can either:
• Reference a defined J2EE data source by name in the <sql:query> or <sql:update> tags
Or
• Create a data source by using a <sql:setDataSource> tag:
<sql:setDataSource driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:ORCL" user="oe" password="oe" var="myDS" />
9-26 Copyright © 2005, Oracle. All rights reserved.
Querying Using SQL Tags
<sql:query datasource="jdbc/oeCoreDS" var="customers" maxRows="10">SELECT * FROM customers</sql:query>
<table><c:forEach var="row" items="${customers.rowsByIndex}"> <tr><c:forEach var="column" items="${row}"> <td><c:out value="${column}"/></td>
</c:forEach></tr></c:forEach> </table>
9-27 Copyright © 2005, Oracle. All rights reserved.
Inserting, Updating, and Deleting Data
Use the <sql:update> tag to insert, update, or delete data. For example:
<sql:update var="rows">UPDATE customers SET account_mgr_id=147WHERE account_mgr_id=149</sql:update><c:out value="${rows}"/> Rows Updated.
9-28 Copyright © 2005, Oracle. All rights reserved.
Formatting Tags
Formatting Tags are used to specify how numbers, dates, and times, should be formatted and parsed in a locale-sensitive manner.
• It is also called "i18n" tags.
• Use either java.util.ResourceBundleor java.util.Locale to format data.
Use the prefix “fmt” in the taglib directive:<%@ taglib uri="http://java.sun.com/jstl/fmt"
prefix="fmt" %>
9-29 Copyright © 2005, Oracle. All rights reserved.
Internationalization Concepts
There are three main considerations for internationalizing an application:
• Locale (geographical or political region)
• Resource bundle (set of paired messages and keys)
• Basename (identifier for a resource bundle)
9-30 Copyright © 2005, Oracle. All rights reserved.
Internationalizing Strings
• To look up a message in a resource bundle, using the current locale, specify the key attribute in the <fmt:message> tag:
• Alternatively, specify the basename to use with the <fmt:bundle> tag:
<fmt:bundle basename="login"><fmt:message key="Hello" /></fmt:bundle>
<fmt:message key="Hello" />
9-31 Copyright © 2005, Oracle. All rights reserved.
Formatting Numbers and Dates
There are several formatting tags for working with numbers and dates, including:
• <fmt:formatNumber>: Specify how a percentage, currency, or number should appear using patterns and locales
• <fmt:formatDate>: Specify how a date and/or time should appear using patterns, locales, and time zones
<fmt:formatNumber type="percent" value=".547" pattern="#.###" />
9-33 Copyright © 2005, Oracle. All rights reserved.
Formatting Numbers and Dates
To reverse the formatting that is executed by the format tags, use the following tags:
• <fmt:parseNumber>: Parses a number into a currency, percent, or number
• <fmt:parseDate>: Parses a date in a customized or a locale-specific manner– Specify the way the date string should be formatted
by using the pattern or parseLocale attributes.
9-34 Copyright © 2005, Oracle. All rights reserved.
Transforming XML Documents
XML uses XSLT stylesheets to transform data. You can accomplish the same by using the <x:transform> tag:
<c:import url="Customers.xml" var="xml"/><c:import url="customerDisplay.xsl" var="MyStyleSheet" /> <x:transform xml="${xml}" xslt="${MyStylesheet}" />
9-35 Copyright © 2005, Oracle. All rights reserved.
JSTL in JDeveloper
• JDeveloper includes all four libraries of the JSP Standard Tag Libraries in the component palette.
• The Design editor resolves the output of the tag, as with any other JSP element.
9-36 Copyright © 2005, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
• Develop custom tags for use in JSP applications
• Add custom tag libraries to the Component Palette
• Use the JSTL custom tag libraries in JSP applications