java中的foreach标签可以实现对集合,map,数组(可以是对象数组,也可以是六种基本数据类型)的遍历。下面的代码是现了foreach标签的功能。
package com.shizhan;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
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 ForeachTag2 extends SimpleTagSupport {
private String var;
private Object item;
private Collection c;
public void setVar(String var) {
this.var = var;
}
public void setItem(Object item) {
this.item=item;
//判断item的类型,全部转换为collection
if(item instanceof Map)
{
Map map=(Map)item;
c=map.entrySet();
}
else if(item instanceof Collection)
{
c=(Collection)item;
}
//判断一个item是否是数组
else if(item.getClass().isArray())
{
//创建一个集合对象
c=new ArrayList();
//取出数组的长度
int length=Array.getLength(item);
for(int i=0;i<length;i++)
{
c.add(Array.get(item, i));
}
}
/**也可以连续遍历八种数据类型,不过比较麻烦
else if(item instanceof Object[])
{
Object[] temp=(Object[]) item;
c=(Collection)Arrays.asList(temp);
}
else if(item instanceof int[])
{
int []temp=(int[]) item;
c=new ArrayList();
for(int i=0;i<temp.length;i++)
{
c.add(temp[i]);
}
}*/
}
@Override
public void doTag() throws JspException, IOException {
Iterator iter=c.iterator();
while(iter.hasNext())
{
Object value=iter.next();
this.getJspContext().setAttribute(var, value);
//通知浏览器更新
this.getJspBody().invoke(null);
}
}
}
jsp测试代码:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@taglib uri="www.shizhan.com" prefix="shizhan"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<%
List<String> a=new ArrayList<String>();
a.add("aaaa");
a.add("bbbb");
a.add("cccc");
request.setAttribute("kk",a);
Map<String,String> map=new HashMap<String,String>();
map.put("111","aaaaa");
map.put("222","bbbbb");
map.put("333","ccccc");
map.put("444","ddddd");
request.setAttribute("map",map);
Integer num[]={1,2,34,56,7888};
request.setAttribute("num",num);
int [] ints={9999,111111,343254325,34654547};
request.setAttribute("ints",ints);
double [] doubles={123.0,34.4,56.7};
request.setAttribute("doubles",doubles);
%>
<shizhan:foreach2 var="ss" item="${kk}">
${ss}
</shizhan:foreach2>
<br> <br> <br>
<shizhan:foreach2 var="entry" item="${map}">
${entry.key } = ${entry.value}
</shizhan:foreach2>
<br> <br>
<shizhan:foreach2 var="i" item="${num }">
${i}
</shizhan:foreach2>
<br> <br>
<shizhan:foreach2 var="x" item="${ints }">
${x}
</shizhan:foreach2>
<br> <br>
<shizhan:foreach2 var="y" item="${doubles }">
${y}
</shizhan:foreach2>
</body>
</html>