对于JSP中的容器,进行迭代的方法最好就是使用标签,当然,SUN提供了JSTL标签库,但是我打算自己开发这个标签。
首先得考虑对于单关键字容器和多关键字容器,分别对应Collection 和Map,然后还有数组还有特殊的八种基本数据类型,这八个基本数据类型因为不是对象所有需要特殊对待。我们使用的方法是是使用反射技术,反射包里面的Array提供了对于所有的数组元素的操作。
下面还是先是实现标签的代码
package com.bird.web.tag.example;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class ForeachTag extends SimpleTagSupport {
private Object items;
private String var;
private Collection<Object> collection;
@SuppressWarnings("unchecked")
public void setItems(Object items) {
this.items = items;
if(items instanceof Collection){
collection = (Collection<Object>) items;
}
if(items instanceof Map){
@SuppressWarnings("rawtypes")
Map map = (Map) items;
collection = map.entrySet();
}
if(items.getClass().isArray()){//这个是最重要的,反射判断
this.collection = new ArrayList();
int length = Array.getLength(items);
for(int i = 0; i < length; i++){
Object value = Array.get(items, i);
collection.add(value);
}
}
}
@Override
public void doTag() throws JspException, IOException {
Iterator it = this.collection.iterator();
while(it.hasNext()){
Object value = it.next();
this.getJspContext().setAttribute(var, value);
this.getJspBody().invoke(null);
}
}
public void setVar(String var) {
this.var = var;
}
}
把所有的容器都转换成Collection 然后使用迭代器进行迭代,这样的代码简洁美观。还有就是将获得的数据按照给定的关键字名称放入到request中进行存储。然后调用invoke方法执行标签体。
下面是tld文件对这个标签的描述
<tag>
<name>Foreach</name>
<tag-class>com.bird.web.tag.example.ForeachTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
然后使用这个标签,当然了,对于8种基本类型,这个标签都是可以进行迭代,和JSTL标签库里面的标签是一样的。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@taglib uri="/example" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>开发迭代标签</title>
</head>
<body>
<%
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
request.setAttribute("list",list);
%>
<c:Foreach items="${list }" var="temp">${temp }</c:Foreach><br/>
<%
Map map = new HashMap();
map.put("aaa","111");
map.put("bbb","222");
map.put("ccc","333");
request.setAttribute("map",map);
%>
<c:Foreach items="${map }" var="temp">${temp }</c:Foreach><br/>
<%
Integer[] i = {1,2,3,4,5,6,7};
request.setAttribute("array",i);
%>
<c:Foreach items="${array }" var="num">${num }</c:Foreach>
<%
int[] t = {9,10,11,12,13};
request.setAttribute("t",t);
%>
<c:Foreach items="${t }" var="m">${m }</c:Foreach>
</body>
</html>