1 / 37

Modularizing JavaServer Pages Development with Tags

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.

dsoucy
Download Presentation

Modularizing JavaServer Pages Development with Tags

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Modularizing JavaServer Pages Development with Tags

  2. 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)

  3. 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.

  4. 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.

  5. 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); } }

  6. <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:

  7. <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

  8. 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. 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.

  10. 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).

  11. 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.

  12. Registering Tag Libraries 4. Select Tools > Manage Libraries. 5. Add the JAR and TLD files to the list of JSP Tag Libraries.

  13. Registering Tag Libraries

  14. Using Tag Insight

  15. 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

  16. 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" %>

  17. 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" />

  18. 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" />

  19. 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>

  20. 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

  21. 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" %>

  22. 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" %>

  23. 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" />

  24. 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>

  25. 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.

  26. 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" %>

  27. 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)

  28. 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>

  29. 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="#.###" />

  30. 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.

  31. 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}" />

  32. 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.

  33. 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

  34. Practice 9-1: Overview • This practice covers creating a JSP that uses the JSTL custom tag library.

More Related