<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标签文件的内容原样输出;
新闻热点
疑难解答