<forEach>中的items類型是map或者Collection類型的
首先還是創建一個標簽處理器類
因為items要迭代各種集合
然後重寫setter方法
聲明一個成員變量
在items的setter方法中
然後繼承他的doTag方法
public class ForEachTag
private String var;
private Object items;
private Collection collection;
public void setVar(String var){
this
}
public void setItems(Object items){
this
if(items instanceof Map){
Map map = (Map) items;
collection = map
}
if(items instanceof Collection){//set list
collection =(Collection) items;
}
if(items
collection = new ArrayList();
int len = Array
for(int i=
Object obj= Array
collection
}
}
}
@Override
public void doTag() throws JspException
Iterator iterator = collection
while(iterator
Object obj = iterator
this
this
}
}
}
然後
<tag>
<name>forEach
<tag
<body
<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
map
map
map
map
request
%>
<c:forEach
${str
</c:forEach
<%
String[] strs ={"aa"
request
%>
<c:forEach
${str}<br>
</c:forEach
接下裡是一個轉義的自定義標簽
步驟都一樣
public void doTag() throws JspException
JspFragment jf = this
StringWriter sw = new StringWriter();//獲取一個流對象
jf
String s =sw
s= filter(s);//獲取進行轉義之後的字符
this
}
public String filter(String message) {//對字符串進行轉義的方法
if (message == null)
return (null);
char content[] = new char[message
message
StringBuffer result = new StringBuffer(content
for (int i =
switch (content[i]) {
case
result
break;
case
result
break;
case
result
break;
case
result
break;
default:
result
}
}
return (result
}
}
接下來就一樣了
<tag>
<name>htmlFilter</name>
<tag
<body
</tag>
<c:htmlFilter>
<a href=""> aaa</a>
</c:htmlFilter>
Jsp標簽文件的內容原樣輸出
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20265.html