1 /*
2 * ForEachTag.java
3 *
4 * $Author: mballesteros $ $Date: 2004/02/22 17:39:46 $ $Revision: 1.5 $
5 */
6 package net.sf.ewc.taglib;
7
8 import java.io.IOException;
9 import java.util.Collection;
10 import java.util.Iterator;
11
12 import javax.servlet.jsp.JspException;
13
14 /***
15 * {@link ForEachTag}iterates over all the collection items in the source,
16 * setting each one as the new evaluation context and repeating its content.
17 *
18 * @author mballesteros
19 */
20 public class ForEachTag extends EWCTag {
21
22 /***
23 * Expression to the collection that must be traversed
24 */
25 private String src;
26
27 /***
28 * indexName to use for parameter substitution
29 */
30 private String indexName = "@i";
31
32 /***
33 * Internal loop counter
34 */
35 private int i;
36
37 /***
38 * Iterator
39 */
40 private Iterator it;
41
42 /***
43 * Sets the expression to the collection to iterate over
44 *
45 * @param src
46 * The expression
47 */
48 public void setSrc(String src) {
49 this.src = src;
50 }
51
52 /***
53 * Sets the index name to use when substituting parameters (defaults to
54 * "i")
55 *
56 * @param indexName
57 */
58 public void setIndexName(String indexName) {
59 this.indexName = "@" + indexName;
60 }
61
62 /***
63 * Main constructor
64 */
65 public ForEachTag() {
66 super();
67 }
68
69 /***
70 * @return
71 */
72 public int doStartTag() {
73 Object value = getExpressionValue(src);
74 if (value instanceof Collection) {
75 Collection collection = (Collection) value;
76 if (collection.size() > 0) {
77 i = 0;
78 it = collection.iterator();
79 return EVAL_BODY_TAG;
80 }
81 }
82
83 return SKIP_BODY;
84 }
85
86 /***
87 * @throws JspException
88 */
89 public void doInitBody() throws JspException {
90 this.pushCtx(it.next(), getIndexedExpression(src, Integer.toString(i)));
91 }
92
93 /***
94 * @return How to follow processing
95 * @throws JspException
96 */
97 public int doAfterBody() throws JspException {
98 try {
99 i++;
100 if (it.hasNext()) {
101 popCtx();
102 this.pushCtx(
103 it.next(),
104 getIndexedExpression(src, Integer.toString(i)));
105 return EVAL_BODY_TAG;
106 } else {
107 popCtx();
108 bodyContent.writeOut(bodyContent.getEnclosingWriter());
109 return SKIP_BODY;
110 }
111 } catch (IOException ex) {
112 throw new JspException(ex.getMessage());
113 }
114 }
115
116 /***
117 * Transforms the user expression, substituting the context parameters
118 *
119 * @return
120 */
121 protected String substituteParentParameters(String exp) {
122 if (exp.indexOf(indexName) > -1) {
123 exp = exp.replaceAll(indexName, Integer.toString(i));
124 }
125 return super.substituteParentParameters(exp);
126 }
127 }
This page was automatically generated by Maven