A foreach custom label that implements a foreach (such as list, set, map, various arrays) of any data type, implemented with the Simpletagsuppert subclass
1. Define three variables, VAR and items are the properties of the label, Collection Collection is used to temporarily store the generic type of items, define the Set method
First, create a new Foreachtag class that implements the Simpletagsuppert
Then define the set method as follows
Public voidSetitems (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=NewArrayList (); intLength=array.getlength (items); for(intI=0; i<length;i++) {Collection.add (Array.Get(items, i)); } } } Public voidSetVar (Stringvar) { This.var=var; }View Code
Finally overriding the parent class method Dotag method
@Override publicvoid 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. Configuring the TLD file, a name, two properties
<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 Test
<Body><BR>----------------------LIST----------------------<BR><%List List=NewArrayList (); List.add ("aaaaaa"); List.add ("bbbbbb"); List.add ("CCCCCC"); List.add ("dddddd"); List.add ("eeeeee"); List.add ("FFFFFF"); Request.setattribute ("List", list);%><J:foreachItems= "${list}"var= "Str">${str}</J:foreach><BR><BR>---------------------MAP-----------------------<BR><%map Map=NewHashMap (); 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:foreachItems= "${map}"var= "Str">${str.key}.....${str.value};</J:foreach><BR><BR>-------------------------------ARRAY-------------------------------<BR>----------------------INT----------------------<BR><% int[]inum=New int[]{Ten, +, Wu,265}; Request.setattribute ("Inum", inum);%><J:foreachItems= "${inum}"var= "Str">${str}</J:foreach><BR>----------------------BOOLEAN----------------------<BR><% Boolean[] Bnum=New Boolean[]{true,true,false,true,false}; Request.setattribute ("Bnum", bnum);%><J:foreachItems= "${bnum}"var= "Str">${str}</J:foreach><BR>----------------------daoble----------------------<BR><% Doublednum[]=New Double[]{1.2,5521.12, Wu,36.5,8485.5}; Request.setattribute ("Dnum", dnum);%><J:foreachItems= "${dnum}"var= "Str">${str}</J:foreach></Body>View Code
Custom Label foreach