您的位置:首页 > 其它

学习笔记:自定义标签 foreach

2013-11-03 22:08 274 查看
实现自定义标签的步骤:

//1.继承SimpleTagSurpport类
//2.复写doTag()方法
//3.tld文件中配置
//4.jsp文件中导入


sun公司的部分源码为:

if(items instanceof Object[]){
Object arg[] = (Object[]) items;
collection = Arrays.asList(arg);  //list
}

if(items instanceof int[]){
int temp[] = (int[])items;
collection = new ArrayList();
for(int num : temp){
collection.add(num);
}
}
if(items instanceof short[]){

}
if(items instanceof byte[]){

}

基本数组类型的时候,相同的代码写了八次。

利用Object的getclass方法 可以简化:
public class ForEachTag extends SimpleTagSupport {

private Object iteams;
private String var; //用string 作为一个名字而已; jsp中会用 var='name'; ${name}
private Collection collection;

public void setIteams(Object iteams) {
this.iteams = iteams;
if(iteams instanceof Collection){
collection = (Collection) iteams;
}
if(iteams instanceof Map){
Map map = (Map) iteams;
collection = map.entrySet();
}
if(iteams.getClass().isArray()){
collection = new ArrayList();
int len = Array.getLength(iteams);//这利用了反射*
for(int i=0; i<len;i++){
Object obj = Array.get(iteams, i);
collection.add(obj);
}
}
}
public void setVar(String var) {
this.var = var;
}

public void doTag() throws JspException, IOException {
PageContext pagecontext = (PageContext) this.getJspContext();
Iterator it = collection.iterator();
while(it.hasNext()){
Object obj = it.next();
pagecontext.setAttribute(var,obj);
this.getJspBody().invoke(null);
}
}
}

tld文件的配置:

<tag>
<name>foreach</name>
<tag-class>cn.tanc.web.tag.ForEachTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>iteams</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>


然后就可以使用:

<%@taglib uri="/****" prefix="***" %>
<***:foreach iteams="" var="">
balabalabala
</***:foreach>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: