2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library Dynamic Attribute or Deferred Expression Encapsulating Reusable Content Using Tag Files Declaring Tag Attributes in Tag Files Declaring Tag Variables in Tag Files Evaluating Fragments Passed to Tag Files Top-Level Tag Library Descriptor Elements Declaring Tag Attributes for Tag Handlers Declaring Tag Variables for Tag Handlers Programming Simple Tag Handlers Including Tag Handlers in Web Applications How Is a Simple Tag Handler Invoked? Tag Handlers for Tags with Attributes Defining Attributes in a Tag Handler Setting Deferred Value Attributes and Deferred Method Attributes Tag Handlers for Tags with Bodies Tag Handler Does Not Manipulate the Body Tag Handlers for Tags That Define Variables 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Encapsulating Reusable Content Using Tag FilesA tag file is a source file that contains a fragment of JSPcode that is reusable as a custom tag. Tag files allow you tocreate custom tags using JSP syntax. Just as a JSP page gets translatedinto a servlet class and then compiled, a tag file gets translated intoa tag handler and then compiled. The recommended file extension for a tag file is.tag. As is thecase with JSP files, the tag can be composed of a topfile that includes other files that contain either a complete tag or afragment of a tag file. Just as the recommended extension for a fragmentof a JSP file is.jspf, the recommended extension for a fragmentof a tag file is.tagf. The following version of the Hello, World application introduced inChapter 3, Getting Started with Web Applications uses atag to generate the response. Theresponse tag, which accepts two attributes (agreeting string and a name) is encapsulated inresponse.tag: <%@ attribute name="greeting" required="true" %><%@ attribute name="name" required="true" %><h2><font color="black">${greeting}, ${name}!</font></h2>The highlighted line in thegreeting.jsp page invokes theresponse tag if thelength of theusername request parameter is greater than0: <%@ taglib tagdir="/WEB-INF/tags" prefix="h" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %><html><head><title>Hello</title></head><body bgcolor="white"><img src="duke.waving.gif"> <c:set var="greeting" value="Hello" /> <h2>${greeting}, my name is Duke. What’s yours?</h2><form method="get"><input type="text" name="username" size="25"><p></p><input type="submit" value="Submit"><input type="reset" value="Reset"></form><c:if test="${fn:length(param.username) > 0}" ><h:response greeting="${greeting}"name="${param.username}"/></c:if></body></html>To deploy and run thehello3 application with NetBeans IDE, follow these steps:
To deploy and run thehello3 application with Ant, follow these steps:
To learn how to configure the example, refer to the deployment descriptor (theweb.xml file), which includes the following configurations:
Tag File LocationTag files can be placed in one of two locations: in the/WEB-INF/tags/directory or subdirectory of a web application or in a JAR file (seePackaged Tag Files) in the/WEB-INF/lib/ directory of a web application. Packaged tag files requirea tag library descriptor (seeTag Library Descriptors), an XML document that contains information about alibrary as a whole and about each tag contained in the library. Tagfiles that appear in any other location are not considered tag extensions andare ignored by the web container. Tag File DirectivesDirectives are used to control aspects of tag file translation to a taghandler, and to specify aspects of the tag, attributes of the tag, andvariables exposed by the tag.Table 8-1 lists the directives that you can usein tag files. Table 8-1 Tag File Directives
Declaring TagsThetag directive is similar to the JSP page’s page directive but appliesto tag files. Some of the elements in thetag directive appearin thetag element of a TLD (seeDeclaring Tag Handlers).Table 8-2 lists the tagdirective attributes. Table 8-2tag Directive Attributes
body-content AttributeYou specify the type of a tag’s body content using thebody-contentattribute: bodycontent="empty | scriptless | tagdependent" You must declare the body content of tags that do not accepta body asempty. For tags that have a body there are twooptions. Body content containing custom and standard tags and HTML text is specified asscriptless. All other types of body content (for example, SQL statements passed tothequery tag) is specified astagdependent. If no attribute is specified,the default isscriptless. Declaring Tag Attributes in Tag FilesTo declare the attributes of a custom tag defined in a tag file,you use theattribute directive. A TLD has an analogousattribute element (seeDeclaring Tag Attributes for Tag Handlers).Table 8-3 lists theattribute directive attributes. Table 8-3attribute Directive Attributes Declaring Tag Variables in Tag FilesTag attributes are used to customize tag behavior much as parameters are usedto customize the behavior of object methods. In fact, using tag attributes andEL variables, it is possible to emulate various types of parameters:IN,OUT, and nested. To emulateIN parameters, use tag attributes. A tag attribute is communicated betweenthe calling page and the tag file when the tag is invoked. Nofurther communication occurs between the calling page and the tag file. To emulateOUT or nested parameters, use EL variables. The variable is notinitialized by the calling page but instead is set by the tag file.Each type of parameter is synchronized with the calling page at various pointsaccording to the scope of the variable. SeeVariable Synchronization for details. To declare an EL variable exposed by a tag file, you use thevariable directive. A TLD has an analogousvariable element (seeDeclaring Tag Variables for Tag Handlers).Table 8-4 liststhevariable directive attributes. Table 8-4variable Directive Attributes
Variable SynchronizationThe web container handles the synchronization of variables between a tag file anda calling page.Table 8-5 summarizes when and how each object is synchronized accordingto the object’s scope. Table 8-5 Variable Synchronization Behavior
Ifname-given is used to specify the variable name, then the name ofthe variable in the calling page and the name of the variable inthe tag file are the same and are equal to the valueofname-given. Thename-from-attribute andalias attributes of thevariable directive can be used tocustomize the name of the variable in the calling page while another nameis used in the tag file. When using these attributes, you set thename of the variable in the calling page from the value ofname-from-attributeat the time the tag was called. The name of the corresponding variablein the tag file is the value ofalias. Synchronization ExamplesThe following examples illustrate how variable synchronization works between a tag file andits calling page. All the example JSP pages and tag files reference theJSTL core tag library with the prefixc. The JSP pages reference atag file located in/WEB-INF/tags with the prefixmy.
Evaluating Fragments Passed to Tag FilesWhen a tag file is executed, the web container passes it twotypes of fragments: fragment attributes and the tag body. Recall from the discussion offragment attributes that fragments are evaluated by the tag handler as opposed tothe web container. Within a tag file, you use thejsp:invoke element toevaluate a fragment attribute and use thejsp:doBody element to evaluate a tagfile body. The result of evaluating either type of fragment is sent to the responseor is stored in an EL variable for later manipulation. To store theresult of evaluating a fragment to an EL variable, you specify thevarorvarReader attribute. Ifvar is specified, the container stores the result in anEL variable of typeString with the name specified byvar. IfvarReader is specified, the container stores the result in an EL variable oftypejava.io.Reader, with the name specified byvarReader. TheReader object can then bepassed to a custom tag for further processing. A translation error occurs ifbothvar andvarReader are specified. An optionalscope attribute indicates the scope of the resulting variable. The possiblevalues arepage (default),request,session, orapplication. A translation error occurs ifyou use this attribute without specifying thevar orvarReader attribute. Custom Tag ExamplesThis section introduces examples that demonstrate using custom tags. Simple Attribute ExampleThe Duke’s BookstoreshipDate tag, defined intut-install/javaeetutorial5/examples/web/bookstore3/web/WEB-INF/tags/shipDate.tag, is a custom tagthat has a simple attribute. The tag generates the date of a bookorder according to the type of shipping requested. <%@ taglib prefix="sc" tagdir="/WEB-INF/tags" %><h3><fmt:message key="ThankYou"/> ${param.cardname}.</h3><br><fmt:message key="With"/> <em><fmt:message key="${param.shipping}"/></em>, <fmt:message key="ShipDateLC"/><sc:shipDate shipping="${param.shipping}" />The tag determines the number of days until shipment from theshippingattribute passed to it by the pagetut-install/javaeetutorial5/examples/web/bookstore3/web/bookreceipt.jsp. From the number ofdays, the tag computes the ship date. It then formats the ship date. <%@ attribute name="shipping" required="true" %><jsp:useBean /><jsp:useBean /><c:choose> <c:when test="${shipping == ’QuickShip’}"> <c:set var="days" value="2" /> </c:when> <c:when test="${shipping == ’NormalShip’}"> <c:set var="days" value="5" /> </c:when> <c:when test="${shipping == ’SaverShip’}"> <c:set var="days" value="7" /> </c:when></c:choose><jsp:setProperty name="shipDate" property="time" value="${now.time + 86400000 * days}" /><fmt:formatDate value="${shipDate}" type="date" dateStyle="full"/>.<br><br>Simple and Fragment Attribute and Variable ExampleThe Duke’s Bookstorecatalog tag, defined intut-install/javaeetutorial5/examples/web/bookstore3/web/WEB-INF/tags/catalog.tag, is a custom tag withsimple and fragment attributes and variables. The tag renders the catalog of abook database as an HTML table. The tag file declares that it setsvariables namedprice andsalePrice usingvariable directives. The fragmentnormalPrice usesthe variableprice, and the fragmentonSale uses the variablesprice andsalePrice. Before the tag invokes the fragment attributes using thejsp:invoke element,the web container passes values for the variables back to the calling page. <%@ attribute name="bookDB" required="true" type="database.BookDB" %><%@ attribute name="color" required="true" %><%@ attribute name="normalPrice" fragment="true" %><%@ attribute name="onSale" fragment="true" %><%@ variable name-given="price" %> <%@ variable name-given="salePrice" %><center><table><c:forEach var="book" begin="0" items="${bookDB.books}"> <tr> <c:set var="bookId" value="${book.bookId}" /> <td bgcolor="${color}"> <c:url var="url" value="/bookdetails" > <c:param name="bookId" value="${bookId}" /> </c:url> <a href="${url}">< strong>${book.title} </strong></a></td> <td bgcolor="${color}" rowspan=2> <c:set var="salePrice" value="${book.price * .85}" /> <c:set var="price" value="${book.price}" /> <c:choose> <c:when test="${book.onSale}" > <jsp:invoke fragment="onSale" /> </c:when> <c:otherwise> <jsp:invoke fragment="normalPrice"/> </c:otherwise> </c:choose> </td> ...</table></center>The pagebookcatalog.jsp invokes thecatalog tag that has the simple attributesbookDB,which contains catalog data, andcolor, which customizes the coloring of the table rows.The formatting of the book price is determined by two fragment attributes,normalPrice andonSale, that are conditionally invoked by the tag according to dataretrieved from the book database. <sc:catalog bookDB ="${bookDB}" color="#cccccc"> <jsp:attribute name="normalPrice"> <fmt:formatNumber value="${price}" type="currency"/> </jsp:attribute> <jsp:attribute name="onSale"> <strike> <fmt:formatNumber value="${price}" type="currency"/> </strike><br/> <font color="red"> <fmt:formatNumber value="${salePrice}" type="currency"/> </font> </jsp:attribute></sc:catalog>The screen produced bytut-install/javaeetutorial5/examples/web/bookstore3/web/bookcatalog.jsp is shown inFigure 8-2. You can compare itto the version inFigure 5-2. Figure 8-2 Book Catalog ![]() Dynamic Attribute ExampleThe following code implements the tag discussed inDynamic Attributes. An arbitrary number of attributeswhose values are colors are stored in aMap named by thedynamic-attributesattribute of thetag directive. The JSTLforEach tag is used to iteratethrough theMap and the attribute keys and colored attribute values areprinted in a bulleted list. <%@ tag dynamic-attributes="colorMap"%><ul><c:forEach var="color" begin="0" items="${colorMap}"> <li>${color.key} = <font color="${color.value}">${color.value}</font></li></c:forEach></ul>Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |