延續上篇,完整實作支援 Map、Collection、陣列的 <c:forEach2> 標籤,以及將標籤體內容進行 HTML 轉義的 <c:htmlFilter> 標籤。
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) {
collection = ((Map) items).entrySet();
} else if (items instanceof Collection) {
collection = (Collection) items;
} else if (items.getClass().isArray()) {
collection = new ArrayList();
int len = Array.getLength(items);
for (int i = 0; i < len; i++) collection.add(Array.get(items, i));
}
}
@Override
public void doTag() throws JspException, IOException {
Iterator it = collection.iterator();
while (it.hasNext()) {
Object obj = it.next();
this.getJspContext().setAttribute(var, obj);
this.getJspBody().invoke(null);
}
}
}
<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>
<% Map map = new HashMap(); map.put("aa","aaaa"); ... 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 class HTMLFilter extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
JspFragment jf = this.getJspBody();
StringWriter sw = new StringWriter();
jf.invoke(sw);
String s = filter(sw.toString());
this.getJspContext().getOut().write(s);
}
private String filter(String msg) {
if (msg == null) return null;
StringBuffer sb = new StringBuffer(msg.length() + 50);
for (char c : msg.toCharArray()) {
switch (c) {
case '<': sb.append("<"); break;
case '>': sb.append(">"); break;
case '&': sb.append("&"); break;
case '"': sb.append("""); break;
default: sb.append(c);
}
}
return sb.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> <!-- 頁面顯示:<a href=""> aaa</a> -->