2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library Initializing and Finalizing a JSP Page Programming Tags That Accept Scripting Elements How Is a Classic Tag Handler Invoked? Tag Handler Does Not Manipulate the Body 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 | Programming Tags That Accept Scripting ElementsTags that accept scripting elements in attribute values or in the body cannotbe programmed as simple tags; they must be implemented as classic tags. Thefollowing sections describe the TLD elements and JSP tag extension API specific toclassic tag handlers. All other TLD elements are the same as for simpletags. TLD ElementsYou specify the character of a classic tag’s body content using thebody-contentelement: <body-content>empty | JSP | tagdependent</body-content> You must declare the body content of tags that do not havea body asempty. For tags that have a body, there aretwo options. Body content containing custom and core tags, scripting elements, and HTMLtext is categorized asJSP. All other types of body content (for example,SQL statements passed to thequery tag) are labeledtagdependent. Tag HandlersThe classes and interfaces used to implement classic tag handlers are contained inthejavax.servlet.jsp.tagext package. Classic tag handlers implement either theTag, theIterationTag, or theBodyTag interface. Interfaces can be used to take an existing Java object andmake it a tag handler. For newly created classic tag handlers, you canuse theTagSupport andBodyTagSupport classes as base classes. These classes andinterfaces are contained in thejavax.servlet.jsp.tagext package. Tag handler methods defined by theTag andBodyTag interfaces are calledby the JSP page’s servlet at various points during the evaluation of thetag. When the start element of a custom tag is encountered, the JSPpage’s servlet calls methods to initialize the appropriate handler and then invokes the handler’sdoStartTag method. When the end element of a custom tag is encountered, thehandler’sdoEndTag method is invoked for all but simple tags. Additional methods areinvoked in between when a tag handler needs to manipulate the body ofthe tag. For further information, seeTags with Bodies. To provide a tag handler implementation, youmust implement the methods, summarized inTable 9-2, that are invoked at various stagesof processing the tag. Table 9-2 Tag Handler Methods
A tag handler has access to an API that allows it tocommunicate with the JSP page. The entry points to the API are twoobjects: the JSP context (javax.servlet.jsp.JspContext) for simple tag handlers and the page context (javax.servlet.jsp.PageContext) forclassic tag handlers.JspContext provides access to implicit objects.PageContext extendsJspContext with HTTP-specificbehavior. A tag handler can retrieve all the other implicit objects (request, session,and application) that are accessible from a JSP page through these objects. Inaddition, implicit objects can have named attributes associated with them. Such attributes areaccessed using[set|get]Attribute methods. If the tag is nested, a tag handler also has access tothe handler (called theparent) associated with the enclosing tag. How Is a Classic Tag Handler Invoked?TheTag interface defines the basic protocol between a tag handler and aJSP page’s servlet. It defines the life cycle and the methods tobe invoked when the start and end tags are encountered. The JSP page’s servlet invokes thesetPageContext,setParent, and attribute-setting methods beforecallingdoStartTag. The JSP page’s servlet also guarantees thatrelease will be invokedon the tag handler before the end of the page. Here is a typical tag handler method invocation sequence: ATag t = new ATag();t.setPageContext(...);t.setParent(...);t.setAttribute1(value1);t.setAttribute2(value2);t.doStartTag();t.doEndTag();t.release(); TheBodyTag interface extendsTag by defining additional methods that let a taghandler access its body. The interface provides three new methods:
A typical invocation sequence is as follows: t.doStartTag();out = pageContext.pushBody();t.setBodyContent(out);// perform any initialization needed after body content is sett.doInitBody();t.doAfterBody();// while doAfterBody returns EVAL_BODY_AGAIN we // iterate body evaluation...t.doAfterBody();t.doEndTag();out = pageContext.popBody();t.release(); Tags with BodiesA tag handler for a tag with a body is implemented differently dependingon whether or not the tag handler needs to manipulate the body. Atag handler manipulates the body when it reads or modifies the contents ofthe body. Tag Handler Does Not Manipulate the BodyIf the tag handler does not need to manipulate the body, thetag handler should implement theTag interface. If the tag handler implements theTaginterface and the body of the tag needs to be evaluated, thedoStartTagmethod must returnEVAL_BODY_INCLUDE; otherwise it should returnSKIP_BODY. If a tag handler needs to iteratively evaluate the body, it shouldimplement theIterationTag interface. The tag handler should returnEVAL_BODY_AGAIN from thedoAfterBodymethod if it determines that the body needs to be evaluated again. Tag Handler Manipulates the BodyIf the tag handler needs to manipulate the body, the tag handlermust implementBodyTag (or must be derived fromBodyTagSupport). When a tag handler implements theBodyTag interface, it must implement thedoInitBodyand thedoAfterBody methods. These methods manipulate body content passed to the taghandler by the JSP page’s servlet. ABodyContent object supports several methods to read and write its contents. Atag handler can use the body content’sgetString orgetReader method toextract information from the body, and thewriteOut(out) method to write the body contentsto anout stream. The writer supplied to thewriteOut method is obtainedusing the tag handler’sgetPreviousOut method. This method is used to ensurethat a tag handler’s results are available to an enclosing tag handler. If the body of the tag needs to be evaluated, thedoStartTagmethod must returnEVAL_BODY_BUFFERED; otherwise, it should returnSKIP_BODY. doInitBody MethodThedoInitBody method is called after the body content is set but beforeit is evaluated. You generally use this method to perform any initialization thatdepends on the body content. doAfterBody MethodThedoAfterBody method is calledafter the body content is evaluated.doAfterBody mustreturn an indication of whether to continue evaluating the body. Thus, if thebody should be evaluated again, as would be the case if you wereimplementing an iteration tag,doAfterBody should returnEVAL_BODY_AGAIN; otherwise,doAfterBody should returnSKIP_BODY. The following example reads the content of the body (which contains an SQLquery) and passes it to an object that executes the query. Because thebody does not need to be reevaluated,doAfterBody returnsSKIP_BODY. public class QueryTag extends BodyTagSupport { public int doAfterBody() throws JspTagException { BodyContent bc = getBodyContent(); // get the bc as string String query = bc.getString(); // clean up bc.clearBody(); try { Statement stmt = connection.createStatement(); result = stmt.executeQuery(query); } catch (SQLException e) { throw new JspTagException("QueryTag: " + e.getMessage()); } return SKIP_BODY; }}release MethodA tag handler should reset its state and release any private resources intherelease method. Cooperating TagsTags cooperate by sharing objects. JSP technology supports two styles of object sharing. The first style requires that a shared object be named and storedin the page context (one of the implicit objects accessible to JSP pagesas well as tag handlers). To access objects created and named by anothertag, a tag handler uses thepageContext.getAttribute(name,scope) method. In the second style of object sharing, an object created by theenclosing tag handler of a group of nested tags is available to allinner tag handlers. This form of object sharing has the advantage that ituses a private namespace for the objects, thus reducing the potential for namingconflicts. To access an object created by an enclosing tag, a tag handlermust first obtain its enclosing tag using the static methodTagSupport.findAncestorWithClass(from,class) or theTagSupport.getParent method. The former method should be used when a specific nesting oftag handlers cannot be guaranteed. After the ancestor has been retrieved, a taghandler can access any statically or dynamically created objects. Statically created objects aremembers of the parent. Private objects can also be created dynamically. Such objects canbe stored in a tag handler using thesetValue method and can beretrieved using thegetValue method. The following example illustrates a tag handler that supports both the named approachand the private object approach to sharing objects. In the example, the handlerfor a query tag checks whether an attribute namedconnectionId has beenset. If theconnection attribute has been set, the handler retrieves the connectionobject from the page context. Otherwise, the tag handler first retrieves the taghandler for the enclosing tag and then retrieves the connection object from thathandler. public class QueryTag extends BodyTagSupport { public int doStartTag() throws JspException { String cid = getConnectionId(); Connection connection; if (cid != null) { // there is a connection id, use it connection =(Connection)pageContext. getAttribute(cid); } else { ConnectionTag ancestorTag = (ConnectionTag)findAncestorWithClass(this, ConnectionTag.class); if (ancestorTag == null) { throw new JspTagException("A query without a connection attribute must be nested within a connection tag."); } connection = ancestorTag.getConnection(); ... } }}The query tag implemented by this tag handler can be used ineither of the following ways: <tt:connection cid="con01" ... > ... </tt:connection><tt:query connectionId="con01"> SELECT account, balance FROM acct_table where customer_number = ? <tt:param value="${requestScope.custNumber}" /></tt:query><tt:connection ... > <tt:query cid="balances"> SELECT account, balance FROM acct_table where customer_number = ? <tt:param value="${requestScope.custNumber}" /> </tt:query></tt:connection>The TLD for the tag handler use the following declaration to indicate thattheconnectionId attribute is optional: <tag> ... <attribute> <name>connectionId</name> <required>false</required> </attribute></tag> Tags That Define VariablesThe mechanisms for defining variables in classic tags are similar to those describedinChapter 8, Custom Tags in JSP Pages. You must declare the variable in avariable element of theTLD or in a tag extra info class. UsePageContext().setAttribute(name,value) orPageContext.setAttribute(name,value,scope) methodsin the tag handler to create or update an association between a namethat is accessible in the page context and the object that is thevalue of the variable. For classic tag handlers,Table 9-3 illustrates how the availability ofa variable affects when you may want to set or update the variable’svalue. Table 9-3 Variable Availability
A variable defined by a custom tag can also be accessed ina scripting expression. For example, the web service described in the preceding section canbe encapsulated in a custom tag that returns the response in avariable named by thevar attribute, and thenvar can be accessed in ascripting expression as follows: <ws:hello var="response" name="<%=request.getParameter("username")%>" /><h2><font color="black"><%= response %>!</font></h2>Remember that in situations where scripting is not allowed (in a tag bodywhere thebody-content is declared asscriptless and in a page wherescripting is specified to be invalid), you wouldn’t be able to access thevariable in a scriptlet or an expression. Instead, you would have to usethe JSP expression language to access the variable. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |