1 package jodd.servlet.tags.basic; 2 3 import java.io.IOException; 4 import java.util.Collection; 5 import java.util.Iterator; 6 7 import javax.servlet.jsp.JspTagException; 8 import javax.servlet.jsp.tagext.BodyContent; 9 import javax.servlet.jsp.tagext.BodyTagSupport; 10 11 22 public class IteratorTag extends BodyTagSupport { 23 24 public final static String ELEMENT_NAME = "element"; 25 public final static String COUNT_NAME = "count"; 26 public final static String TOTAL_NAME = "total"; 27 public final static String INDEX_NAME = "index"; 28 29 private Iterator iterator = null; 30 private int index; 31 private Integer total; 32 private int count; 33 34 public void setCollection(Collection c) { 35 if (c.size() > 0) { 36 iterator = c.iterator(); 37 total = new Integer(c.size()); 38 } 39 } 40 41 private int offset = 0; 42 public void setOffset(int i) { 43 offset = i; 44 } 45 46 private int lengthValue = 0; 47 private String length = null; 48 public void setLength(String s) { 49 length = s; 50 } 51 52 private void doIterator(Iterator i) { 53 pageContext.setAttribute(ELEMENT_NAME, i.next()); 54 pageContext.setAttribute(COUNT_NAME, new Integer(count)); 55 pageContext.setAttribute(TOTAL_NAME, total); 56 pageContext.setAttribute(INDEX_NAME, new Integer(index)); 57 count++; 58 index++; 59 lengthValue--; 60 } 61 62 public int doStartTag() { 63 if (iterator == null) { 64 return SKIP_BODY; 65 } 66 count = 0; index = 0; 69 if (length == null) { lengthValue = total.intValue(); 71 } else { 72 lengthValue = Integer.parseInt(length); 73 } 74 if (lengthValue <= 0) { return SKIP_BODY; 76 } 77 78 if (offset < 0) { offset = 0; 80 } 81 while (offset > 0) { 82 if (iterator.hasNext()) { 83 iterator.next(); 84 offset--; 85 index++; 86 } else { 87 return SKIP_BODY; } 89 } 90 if (iterator.hasNext()) { 91 doIterator(iterator); 92 return EVAL_BODY_AGAIN; 93 } else { 94 return SKIP_BODY; 95 } 96 } 97 98 public int doAfterBody() throws JspTagException { 99 BodyContent body = getBodyContent(); 100 try { 101 body.writeOut(getPreviousOut()); 102 } catch (IOException ioe) { 103 throw new JspTagException("IteratorTag: " + ioe.getMessage()); 104 } 105 body.clearBody(); 106 107 if (lengthValue > 0) { 108 if (iterator.hasNext()) { 109 doIterator(iterator); 110 return EVAL_BODY_AGAIN; 111 } 112 } 113 return SKIP_BODY; 114 } 115 116 public int doEndTag() { 117 return EVAL_PAGE; 118 } 119 } 120 | Popular Tags |