Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

The Example JSP Pages

Using Scripting

Disabling Scripting

JSP Declarations

Initializing and Finalizing a JSP Page

JSP Scriptlets

JSP Expressions

Programming Tags That Accept Scripting Elements

TLD Elements

Tag Handlers

How Is a Classic Tag Handler Invoked?

Tags with Bodies

Tag Handler Does Not Manipulate the Body

Tag Handler Manipulates the Body

Cooperating Tags

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

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

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

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Programming Tags That Accept Scripting Elements

Tags 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 Elements

You 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 Handlers

The 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

Tag Type

Interface

Methods

Basic

Tag

doStartTag,doEndTag

Attributes

Tag

doStartTag,doEndTag,setAttribute1,...,N,release

Body

Tag

doStartTag,doEndTag,release

Body, iterativeevaluation

IterationTag

doStartTag,doAfterBody,doEndTag,release

Body, manipulation

BodyTag

doStartTag,doEndTag,release,doInitBody,doAfterBody

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:

  • setBodyContent: Creates body content and adds to the tag handler

  • doInitBody: Called before evaluation of the tag body

  • doAfterBody: Called after evaluation of the tag body

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 Bodies

A 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 Body

If 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 Body

If 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 Method

ThedoInitBody 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 Method

ThedoAfterBody 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 Method

A tag handler should reset its state and release any private resources intherelease method.

Cooperating Tags

Tags 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 Variables

The 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

Value

Availability

In Methods

NESTED

Between the start tag and the end tag

doStartTag,doInitBody, anddoAfterBody

AT_BEGIN

Fromthe start tag until the end of the page

doStartTag,doInitBody,doAfterBody, anddoEndTag

AT_END

After the end tag until the end of the page

doEndTag

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.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp