1 package net.stff.util.tags; 2 3 import java.io.IOException; 4 5 import javax.servlet.jsp.JspException; 6 import javax.servlet.jsp.PageContext; 7 import javax.servlet.jsp.tagext.BodyTagSupport; 8 import javax.servlet.jsp.tagext.IterationTag; 9 import javax.servlet.jsp.tagext.Tag; 10 11 import org.springframework.web.util.ExpressionEvaluationUtils; 12 13 /*** 14 * @author buntekuh 15 * 16 * <br>Implements an EL aware "for" loop. 17 * <br>Loops over an integer range from "from" to "to" incrementing by "step". The current value is stored in a pageContext variable defined by "var". 18 */ 19 public class LoopTag extends BodyTagSupport { 20 21 private int from; 22 private int to; 23 private int step= 1; 24 private String var; 25 26 /*** 27 * 28 * @return Returns the var. 29 */ 30 public String getVar() { 31 return var; 32 } 33 /*** 34 * @param var The var to set. 35 */ 36 public void setVar(String var) { 37 this.var = var; 38 } 39 /*** 40 * @param from The from to set. 41 */ 42 public void setFrom(String from) { 43 try { 44 this.from= ExpressionEvaluationUtils.evaluateInteger("from", from, super.pageContext); 45 } catch (JspException e) { 46 e.printStackTrace(); 47 this.from= 0; 48 } 49 } 50 /*** 51 * @param step The step to set. 52 */ 53 public void setStep(String step) { 54 55 56 try { 57 this.step= ExpressionEvaluationUtils.evaluateInteger("step", step, super.pageContext); 58 } catch (JspException e) { 59 e.printStackTrace(); 60 this.step= 1; 61 } 62 } 63 /*** 64 * @param to The to to set. 65 */ 66 public void setTo(String to) { 67 try { 68 this.to= ExpressionEvaluationUtils.evaluateInteger("to", to, super.pageContext); 69 } catch (JspException e) { 70 e.printStackTrace(); 71 this.to= -1; 72 } 73 } 74 75 public int doStartTag() throws JspException{ 76 77 return from <= to ? IterationTag.EVAL_BODY_AGAIN : Tag.SKIP_BODY; 78 } 79 80 public void doInitBody() throws JspException{ 81 super.pageContext.setAttribute(getVar(), new Integer(from), PageContext.PAGE_SCOPE); 82 } 83 84 public int doAfterBody() throws JspException{ 85 int i = ((Integer)super.pageContext.getAttribute(getVar(), PageContext.PAGE_SCOPE)).intValue(); 86 i += step; 87 if(i <= to){ 88 super.pageContext.setAttribute(getVar(), new Integer(i), PageContext.PAGE_SCOPE); 89 return IterationTag.EVAL_BODY_AGAIN; 90 } 91 else{ 92 try { 93 super.bodyContent.writeOut(super.bodyContent.getEnclosingWriter()); 94 } catch (IOException e) { 95 throw new JspException(e.getMessage()); 96 } 97 return Tag.SKIP_BODY; 98 } 99 } 100 }