⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jsptags7.html

📁 j2eePDF格式的电子书
💻 HTML
📖 第 1 页 / 共 4 页
字号:
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">  <head>    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />    <meta http-equiv="Content-Style-Type" content="text/css" />    <title>Programming Simple Tag Handlers</title>    <link rel="StyleSheet" href="document.css" type="text/css" media="all" />    <link rel="StyleSheet" href="catalog.css" type="text/css" media="all" />    <link rel="Table of Contents" href="J2EETutorialTOC.html" />    <link rel="Previous" href="JSPTags6.html" />    <link rel="Next" href="JSPAdvanced.html" />    <link rel="Index" href="J2EETutorialIX.html" />  </head>  <body>    <table width="550" summary="layout" id="SummaryNotReq1">      <tr>	<td align="left" valign="center">	<font size="-1">	<a href="http://java.sun.com/j2ee/1.4/download.html#tutorial" target="_blank">Download</a>	<br>	<a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/faq.html" target="_blank">FAQ</a>	<br>	<a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/history.html" target="_blank">History</a>	</td>        <td align="center" valign="center"><a accesskey="p" href="JSPTags6.html"><img id="LongDescNotReq1" src="images/PrevArrow.gif" width="26" height="26" border="0" alt="Prev" /></a><a accesskey="c" href="J2EETutorialFront.html"><img id="LongDescNotReq1" src="images/UpArrow.gif" width="26" height="26" border="0" alt="Home" /></a><a accesskey="n" href="JSPAdvanced.html"><img id="LongDescNotReq3" src="images/NextArrow.gif" width="26" height="26" border="0" alt="Next" /></a><a accesskey="i" href="J2EETutorialIX.html"></a>        </td>	<td align="right" valign="center">	<font size="-1">	<a href="http://java.sun.com/j2ee/1.4/docs/api/index.html" target="_blank">API</a>	<br>	<a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/search.html" target="_blank">Search</a>	<br>	<a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html" target="_blank">Feedback</a></font>	</font>	</td>      </tr>    </table>    <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider">    <blockquote><a name="wp90514"> </a><h2 class="pHeading1">Programming Simple Tag Handlers</h2><a name="wp90515"> </a><p class="pBody">The classes and interfaces used to implement simple tag handlers are contained in the <code class="cCode"><a  href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/package-summary.html" target="_blank">javax.servlet.jsp.tagext</a></code> package. Simple tag handlers implement the <code class="cCode"><a  href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/SimpleTag.html" target="_blank">SimpleTag</a></code> interface. Interfaces can be used to take an existing Java object and make it a tag handler. For most newly created handlers, you would use the <code class="cCode"><a  href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/SimpleTagSupport.html" target="_blank">SimpleTagSupport</a></code> classes as a base class.</p><a name="wp90520"> </a><p class="pBody">The heart of a simple tag handler is a single method--<code class="cCode">doTag</code>--which gets invoked when the end element of the tag is encountered. Note that the default implementation of the <code class="cCode">doTag</code> method of <code class="cCode">SimpleTagSupport</code> does nothing. </p><a name="wp90521"> </a><p class="pBody">A tag handler has access to an API that allows it to communicate with the JSP page. The entry point to the API is the JSP context object (<code class="cCode"><a  href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/JspContext.html" target="_blank">javax.servlet.jsp.JspContext)</a></code>. <code class="cCode">JspContext</code> provides access to implicit objects. <code class="cCode">PageContext</code> extends <code class="cCode">JspContext</code> with servlet-specific behavior. A tag handler can retrieve all the other implicit objects (request, session, and application) accessible from a JSP page through these objects. If the tag is nested, a tag handler also has access to the handler (called the <em class="cEmphasis">parent</em>) associated with the enclosing tag.</p><a name="wp90523"> </a><h4 class="pHeading3">Packaging Tag Handlers</h4><a name="wp90524"> </a><p class="pBody">Tag handlers can be made available to a Web application in two basic ways. The classes implementing the tag handlers can be stored in an unpacked form in the <code class="cCode">WEB-INF/classes/</code> subdirectory of the Web application. Alternatively, if the library is distributed as a JAR, it is stored in the <code class="cCode">WEB-INF/lib/</code> directory of the Web application.</p><a name="wp90526"> </a><h4 class="pHeading3">How Is a Simple Tag Handler Invoked?</h4><a name="wp90527"> </a><p class="pBody">The <code class="cCode">SimpleTag</code> interface defines the basic protocol between a simple tag handler and a JSP page's servlet. The JSP page's servlet invokes the <code class="cCode">setJspContext</code>, <code class="cCode">setParent</code>, and attribute setting methods before calling <code class="cCode">doStartTag</code>. </p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">ATag t = new ATag();t.setJSPContext(...);t.setParent(...);t.setAttribute1(value1);t.setAttribute2(value2);...t.setJspBody(new JspFragment(...))t.doTag();<a name="wp90528"> </a></pre></div><a name="wp90529"> </a><p class="pBody">The following sections describe the methods that you need to develop for each type of tag introduced in <a  href="JSPTags4.html#wp89569">Types of Tags</a>.</p><a name="wp90534"> </a><h3 class="pHeading2">Basic Tags</h3><a name="wp90537"> </a><p class="pBody">The handler for a basic tag without a body must implement the <code class="cCode">doTag</code> method of the <code class="cCode">SimpleTag</code> interface. The <code class="cCode">doTag</code> method is invoked when the start tag is encountered.</p><a name="wp90538"> </a><p class="pBody">The basic tag discussed in the first section,</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">&lt;tt:basic /&gt;<a name="wp90539"> </a></pre></div><a name="wp90540"> </a><p class="pBody">would be implemented by the following tag handler:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public HelloWorldSimpleTag extends SimpleTagSupport {&nbsp;&nbsp;public void doTag() throws JspException, IOException {&nbsp;&nbsp;&nbsp;&nbsp;getJspContext().getOut().write(&quot;Hello, world.&quot;);&nbsp;&nbsp;}}<a name="wp90541"> </a></pre></div><a name="wp90543"> </a><h3 class="pHeading2">Tags with Attributes</h3><a name="wp90545"> </a><h4 class="pHeading3">Defining Attributes in a Tag Handler</h4><a name="wp90547"> </a><p class="pBody">For each tag attribute, you must define a set method in the tag handler that conforms to the JavaBeans architecture conventions. For example, the tag handler for the JSTL <code class="cCode">c:if</code> tag,</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">&lt;c:if test=&quot;${Clear}&quot;&gt;<a name="wp90548"> </a></pre></div><a name="wp90549"> </a><p class="pBody">contains the following method:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public void setTest(boolean test) {&nbsp;&nbsp;this.test = test;}<a name="wp90550"> </a></pre></div><a name="wp90551"> </a><h4 class="pHeading3">Attribute Validation</h4><a name="wp90552"> </a><p class="pBody">The documentation for a tag library should describe valid values for tag attributes. When a JSP page is translated, a Web container will enforce any constraints contained in the TLD element for each attribute. </p><a name="wp90555"> </a><p class="pBody">The attributes passed to a tag can also be validated at translation time with the <code class="cCode">validate</code> method of a class derived from <code class="cCode">TagExtraInfo</code>. This class is also used to provide information about variables defined by the tag (see <a  href="JSPTags7.html#wp90643">TagExtraInfo Class</a>).</p><a name="wp90561"> </a><p class="pBody">The <code class="cCode">validate</code> method is passed the attribute information in a <code class="cCode">TagData</code> object, which contains attribute-value tuples for each of the tag's attributes. Since the validation occurs at translation time, the value of an attribute that is computed at request time will be set to <code class="cCode">TagData.REQUEST_TIME_VALUE</code>.</p><a name="wp90562"> </a><p class="pBody">The tag <code class="cCode">&lt;tt:twa</code> <code class="cCode">attr1=&quot;value1&quot;/&gt;</code> has the following TLD <code class="cCode">attribute</code> element:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">&lt;attribute&gt;&nbsp;&nbsp;&lt;name&gt;attr1&lt;/name&gt;&nbsp;&nbsp;&lt;required&gt;true&lt;/required&gt;&nbsp;&nbsp;&lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;&lt;/attribute&gt;<a name="wp90563"> </a></pre></div><a name="wp90564"> </a><p class="pBody">This declaration indicates that the value of <code class="cCode">attr1</code> can be determined at runtime.</p><a name="wp90565"> </a><p class="pBody">The following <code class="cCode">validate </code>method checks that the value of <code class="cCode">attr1</code> is a valid Boolean value. Note that since the value of <code class="cCode">attr1</code> can be computed at runtime, <code class="cCode">validate</code> must check whether the tag user has chosen to provide a runtime value. </p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class TwaTEI extends TagExtraInfo {&nbsp;&nbsp;public ValidationMessage[] validate(TagData data) {&nbsp;&nbsp;&nbsp;&nbsp;Object o = data.getAttribute(&quot;attr1&quot;);&nbsp;&nbsp;&nbsp;&nbsp;if (o != null &amp;&amp; o != TagData.REQUEST_TIME_VALUE) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (((String)o).toLowerCase().equals(&quot;true&quot;) || &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;((String)o).toLowerCase().equals(&quot;false&quot;) ) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return new ValidationMessage(data.getId(),&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;Invalid boolean value.&quot;);&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;else&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;&nbsp;&nbsp;}}<a name="wp90566"> </a></pre></div><a name="wp90567"> </a><h4 class="pHeading3">Dynamic Attributes</h4><a name="wp90568"> </a><p class="pBody">Tag handlers that support dynamic attributes must declare that they do so in the <code class="cCode">tag</code> element of the TLD (see <a  href="JSPTags6.html#wp90277">Declaring Tag Handlers</a>). In addition, your tag handler must implement the <code class="cCode">setDynamicAttribute</code> method of the <code class="cCode">DynamicAttributes</code> interface. For each attribute specified in the tag invocation that does not have a corresponding <code class="cCode">attribute</code> element in the TLD, the Web container calls <code class="cCode">setDynamicAttribute</code>, passing in the namespace of the attribute (or null if in the default namespace), the name of the attribute, and the value of the attribute. You must implement the <code class="cCode">setDynamicAttribute</code> method to remember the names and values of the dynamic attributes so that they can be used later on when <code class="cCode">doTag</code> is executed. If the <code class="cCode">setDynamicAttribute</code> method an exception, the <code class="cCode">doTag</code> method is not invoked for the tag, and the exception must be treated in the same manner as if it came from an attribute setter method. </p><a name="wp90572"> </a><p class="pBody">The following implementation of <code class="cCode">setDynamicAttribute</code> saves the attribute names and values in lists. Then, in the <code class="cCode">doTag</code> method, the names and values are echoed to the response in an HTML list.</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">&nbsp;&nbsp;private ArrayList keys = new ArrayList();&nbsp;&nbsp;private ArrayList values = new ArrayList();&nbsp;&nbsp;public void setDynamicAttribute(String uri, &nbsp;&nbsp;&nbsp;&nbsp;String localName, Object value ) throws JspException {&nbsp;&nbsp;&nbsp;&nbsp;keys.add( localName );&nbsp;&nbsp;&nbsp;&nbsp;values.add( value );}public void doTag() throws JspException, IOException {&nbsp;&nbsp;JspWriter out = getJspContext().getOut();&nbsp;&nbsp;for( int i = 0; i &lt; keys.size(); i++ ) {&nbsp;&nbsp;    String key = (String)keys.get( i );&nbsp;&nbsp;    Object value = values.get( i );&nbsp;&nbsp;    out.println( &quot;&lt;li&gt;&quot; + key + &quot; = &quot; + value + &quot;&lt;/li&gt;&quot; );&nbsp;&nbsp;}}<a name="wp90573"> </a></pre></div><a name="wp90575"> </a><h3 class="pHeading2">Tags with Bodies</h3><a name="wp90577"> </a><p class="pBody">A tag handler for a tag with a body is implemented differently depending on whether or not the tag handler needs to manipulate the body. A tag handler manipulates the body when it reads or modifies the contents of the body. </p><a name="wp90579"> </a><h5 class="pHeading4">Tag Handler Does Not Manipulate the Body</h5><a name="wp90580"> </a><p class="pBody">If a tag handler needs to simply evaluate the body, it gets the body with the <code class="cCode">getJspBody</code> method of <code class="cCode">SimpleTag</code> and then evaluates the body with the <code class="cCode">invoke</code> method. </p><a name="wp90581"> </a><p class="pBody">The following tag handler accepts a <code class="cCode">test</code> parameter and evaluates the body of the tag if the test evaluates to true. The body of the tag is encapsulated in a JSP fragment. If the test is true, the handler retrieves the fragment with the <code class="cCode">getJspBody</code> method. The <code class="cCode">invoke</code> method directs all output to a supplied writer or to the <code class="cCode">JspWriter</code> returned by the <code class="cCode">getOut</code> method of the <code class="cCode">JspContext</code> associated with the tag handler if the writer is <code class="cCode">null</code>.</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class IfSimpleTag extends SimpleTagSupport {&nbsp;&nbsp;private boolean test;&nbsp;&nbsp;public void setTest(boolean test) {&nbsp;&nbsp;&nbsp;&nbsp;this.test = test;&nbsp;&nbsp;}&nbsp;&nbsp;public void doTag() throws JspException, IOException {&nbsp;&nbsp;&nbsp;&nbsp;if(test){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;getJspBody().invoke(null);&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;}}<a name="wp90582"> </a></pre></div><a name="wp90583"> </a><h5 class="pHeading4">Tag Handler Manipulates the Body</h5><a name="wp90584"> </a><p class="pBody">If the tag handler needs to manipulate the body, the tag handler must capture the body in a <code class="cCode">StringWriter</code>. The <code class="cCode">invoke</code> method directs all output to a supplied writer. Then the modified body is written to the <code class="cCode">JspWriter</code> returned by the <code class="cCode">getOut</code> method of the <code class="cCode">JspContext</code>. Thus, a tag that converts its body to upper case could be written as follows:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class SimpleWriter extends SimpleTagSupport {&nbsp;&nbsp;public void doTag() throws JspException, IOException {&nbsp;&nbsp;&nbsp;&nbsp;StringWriter sw = new StringWriter();&nbsp;&nbsp;&nbsp;&nbsp;jspBody.invoke(sw);&nbsp;&nbsp;&nbsp;&nbsp;jspContext().&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;getOut().println(sw.toString().toUpperCase());&nbsp;&nbsp;}}<a name="wp90585"> </a></pre></div><a name="wp90587"> </a><h3 class="pHeading2">Tags That Define Variables</h3><a name="wp90588"> </a><p class="pBody">Similar communication mechanisms exist for communication between JSP page and tag handlers as for JSP pages and tag files. </p><a name="wp90589"> </a><p class="pBody">To emulate <code class="cCode">IN</code> parameters, use tag attributes. A tag attribute is communicated between the calling page and the tag handler when the tag is invoked. No further communication occurs between the calling page and tag handler.</p><a name="wp90590"> </a><p class="pBody">To emulate <code class="cCode">OUT</code> or nested parameters, use variables with availability <code class="cCode">AT_BEGIN</code>, <code class="cCode">AT_END</code>, or <code class="cCode">NESTED</code>. The variable is not initialized by the calling page, but set by the tag handler. </p><a name="wp90591"> </a><p class="pBody">For <code class="cCode">AT_BEGIN</code> availability, the variable is available in the calling page from the start tag until the scope of any enclosing tag. If there&#39;s no enclosing tag, then the variable is available to the end of the page. For <code class="cCode">AT_END</code> availability, the variable is available in the calling page after the end tag until the scope of any enclosing tag. If there&#39;s no enclosing tag, then the variable is available to the end of the page. For nested parameters, the variable is available in the calling page between the start tag and the end tag.</p>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -