iteratortag.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 80 行

JAVA
80
字号
package forum;

import java.util.*;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
 * Given a collection, this tag iterates over each element and makes it
 * available to the page.
 *
 * @author    Simon Brown
 */
public class IteratorTag extends TagSupport {

  /** the fully qualified class name of the elements */
  private String className;

  /** the collection over which this tag should iterate */
  private Collection collection;

  /** the iterator used by this tag */
  private Iterator iterator;

  /**
   * Called when the starting tag is encountered.
   */
  public int doStartTag() throws JspException {
    // setup the iterator to be used
    iterator = collection.iterator();

    if (iterator.hasNext()) {
      // if there are elements, put the first one into the
      // page under the name provided by the "id" attribute
      pageContext.setAttribute(getId(), iterator.next());

      // and include the body
      return EVAL_BODY_INCLUDE;
    } else {
      // there are no elements so skip the body
      return SKIP_BODY;
    }
  }

  /**
   * Called after the body has been evaluated.
   */
  public int doAfterBody() throws JspException {
    if (iterator.hasNext()) {
      // if there are more elements, put the next one into the
      // page under the name provided by the "id" attribute
      pageContext.setAttribute(getId(), iterator.next());

      // and instruct the JSP engine to re-evaluate the body of this tag
      return EVAL_BODY_AGAIN;
    } else {
      // there are no more elements so skip the body
      return SKIP_BODY;
    }
  }

  /**
   * Setter for the className attribute.
   *
   * @param s   a String representing the fully qualified class name
   */
  public void setClassName(String s) {
    this.className = s;
  }

  /**
   * Sets the collection over which this tag should iterate.
   *
   * @param coll    a Collection
   */
  public void setCollection(Collection coll) {
    this.collection = coll;
  }

}

⌨️ 快捷键说明

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