<forEach>中的items類型是map或者Collection類型的,怎樣使用增強for迴圈;
首先還是建立一個標籤處理器類,定義兩個屬性,String var; Object items;
因為items要迭代各種集合,所以要使用Object;
然後重寫setter方法; www.2cto.com
聲明一個成員變數,集合類型的, 和上面兩個屬性是不相同的,這個是用在類裡的,
在items的setter方法中,判斷items的類型
然後繼承他的doTag方法;
public class ForEachTag2 extends SimpleTagSupport {
private String var;
private Object items;
private Collection collection;
public void setVar(String var){
this.var=var;
}
public void setItems(Object items){
this.items=items;
if(items instanceof Map){
Map map = (Map) items;
collection = map.entrySet();
}
if(items instanceof Collection){//set list
collection =(Collection) items;
}
if(items.getClass().isArray()){
collection = new ArrayList();
int len = Array.getLength(items);
for(int i=0;i<len;i++){
Object obj= Array.get(items, i);
collection.add(obj);
}
}
}
@Override
public void doTag() throws JspException, IOException {
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
Object obj = iterator.next();
this.getJspContext().setAttribute(var, obj);
this.getJspBody().invoke(null);
}
}
}
然後,寫tld描述標籤
<tag>
<name>forEach2</name>
<tag-class>com.csdn.items.ForEachTag2</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>var</name>
<required>true</required>
</attribute>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
最後在jsp檔案中寫items的各種類型
<%
Map map = new HashMap();
map.put("aa","aaaa");
map.put("bb","bbbb");
map.put("cc","cccc");
map.put("dd","dddd");
map.put("ee","eeee");
request.setAttribute("map",map);
%>
<c:forEach2 var="str" items="${map}">
${str.key }-----${str.value }<br />
</c:forEach2>
<%
String[] strs ={"aa","bb","cc"} ;
request.setAttribute("strs",strs);
%>
<c:forEach2 var="str" items="${strs}">
${str}<br>
</c:forEach2>
接下裡是一個轉義的自訂標籤:
步驟都一樣:
public void doTag() throws JspException, IOException {
JspFragment jf = this.getJspBody();//擷取jsp檔案中的內容
StringWriter sw = new StringWriter();//擷取一個流對象
jf.invoke(sw);//吧內容放到流對象中
String s =sw.toString();//把jsp內容轉成字串
s= filter(s);//擷取進行轉義之後的字元
this.getJspContext().getOut().write(s);//寫入瀏覽器
}
public String filter(String message) {//對字串進行轉義的方法
if (message == null)
return (null);
char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
default:
result.append(content[i]);
}
}
return (result.toString());
}
}
接下來就一樣了,
<tag>
<name>htmlFilter</name>
<tag-class>com.csdn.items.HTMLFilter</tag-class>
<body-content>scriptless</body-content>
</tag>
<c:htmlFilter>
<a href=""> aaa</a>
</c:htmlFilter>
Jsp標籤檔案的內容原樣輸出;