370 likes | 380 Views
Learn to define, develop custom tags using JSTL, reduce Java scriptlets using tags, and create tag libraries for JSP applications. Discover tag handlers, attributes, and JDeveloper integration.
E N D
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)
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.
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: • Invoke the tag library by using the <jsp:taglib/> directive. • Call the tag in the content of the JSP. • Include the location of the taglib.tld file in the web.xml file.
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); } }
<tlibversion> The tag library’s version <jspversion> The JSP specification version for the library <shortname> A default name for the library <uri> Identifies the tag library location <info> Documentation regarding the library <tagclass> Specifies the class for the individual tag <bodycontent> Set to empty, tagdependent, or JSP 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:
<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> Using a Custom Tag
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>
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.
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).
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.
Registering Tag Libraries 4. Select Tools > Manage Libraries. 5. Add the JAR and TLD files to the list of JSP Tag Libraries.
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
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" %>
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" />
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" />
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>
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
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" %>
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" %>
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" />
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>
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.
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" %>
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)
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:message key="Hello" /> <fmt:bundle basename="login"><fmt:message key="Hello" /></fmt:bundle>
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="#.###" />
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.
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}" />
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.
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
Practice 9-1: Overview • This practice covers creating a JSP that uses the JSTL custom tag library.