自定义标签ForEach
一个可实现任何数据类型的foreach(如List、set、map、各种数组)的foreach自定义标签,用SimpleTagSuppert子类实现
1.定义三个变量,var和items是标签的属性,Collection collection用来临时存储items的一般类型,定义set方法
首先新建实现了SimpleTagSuppert的ForEachTag类
然后定义set方法如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void setItems(Object items) { this.items=items; if(items instanceof Collection){ collection=(Collection) items; } if(items instanceof Map){ Map map=(Map) items; collection=(map.entrySet()); } if(items.getClass().isArray()){ collection=new ArrayList(); int length=Array.getLength(items); for(int i=0;i<length;i++){ collection.add(Array.get(items, i)); } } } public void setVar(String var) { this.var = var; }
最后覆盖父类方法doTag方法
@Override public void doTag() throws JspException, IOException { Iterator it=this.collection.iterator(); while(it.hasNext()){ Object value=it.next(); this.getJspContext().setAttribute(var, value); this.getJspBody().invoke(null); } }
2.配置tld文件,一个name,两个属性
<tag> <name>foreach</name> <tag-class>com.jamsbwo.tag.ForeachTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>var</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>items</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
3.jsp测试
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <br>----------------------LIST----------------------<br> <% List list=new ArrayList(); list.add("aaaaaa"); list.add("BBBBBB"); list.add("cccccc"); list.add("dddddd"); list.add("EEEEEE"); list.add("ffffff"); request.setAttribute("list", list); %> <j:foreach items="${list }" var="str"> ${str } </j:foreach> <br><br>---------------------MAP-----------------------<br> <% Map map=new HashMap(); map.put("0", "aaa"); map.put("1", "bbb"); map.put("2", "ccc"); map.put("3", "ddd"); map.put("4", "eee"); map.put("5", "fff"); map.put("6", "ggg"); request.setAttribute("map", map); %> <j:foreach items="${map }" var="str"> ${str.key }.....${str.value }; </j:foreach> <br><BR>-------------------------------ARRAY-------------------------------<br> ----------------------INT----------------------<br> <% int []inum=new int[]{10,40,54,265}; request.setAttribute("inum", inum); %> <j:foreach items="${inum }" var="str"> ${str } </j:foreach> <br>----------------------BOOLEAN----------------------<br> <% boolean [] bnum=new boolean[]{true,true,false,true,false}; request.setAttribute("bnum", bnum); %> <j:foreach items="${bnum }" var="str"> ${str } </j:foreach> <br>----------------------DAOBLE----------------------<br> <% double dnum[]=new double[]{1.2,5521.12,54,36.5,8485.5}; request.setAttribute("dnum", dnum); %> <j:foreach items="${dnum }" var="str"> ${str } </j:foreach> </body>