自定义标签实现遍历集合

本文介绍了如何将不同类型的集合(如Map、类数组、数组)转化为Collection以便统一处理,并提供了一种自定义标签实现遍历集合的方法。通过将Map的Entry、类数组和数组元素放入Collection,利用Iterator进行遍历,每次遍历将当前对象存入pageContext属性,方便在JSP中获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比较好的方法是,将所有集合化为Collection类型的集合,然后只需处理Collection集合便可。

1.将Map化为Collection,Map的每一个元素即Entry放进Collection即可。

2.将类数组化为Collection,调用Arrays.asList(objs);方法。

3.若此对象为数组类(即items.isArray()返回true),将每一个数组元素放入Collection,比较巧妙的是使用Array.getLength(items);获得items数组长度,Array.get(items, i); 便可以获得items 数组在 i 处的对象值。然后将每个对象加入Collection中。

注意:int[]a ; 与Integer []a; 是完全不同的,前者归于第三类,后者归于第二类。

最后只需要处理Collection便可

Iterator it=collection.iterator();
while(it.hasNext())
{
Object ob=it.next();
this.getJspContext().setAttribute(var, ob);
getJspBody().invoke(null);
}

这个方法也十分巧妙,将传入的var变量设为索引值,将Collection的对象作为结果,放进pageContext的属性中,便于在jsp用$获取到,每一次遍历,都会覆盖前一次的属性值。

package com.example;

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.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;


public class ForEach extends SimpleTagSupport {
	private Object items;
	private String var;
	private Collection collection;
	public Object getItems() {
		return items;
	}
	public void setItems(Object items) {
		this.items = items;
	}
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
	@Override
	public void doTag() throws JspException, IOException {
		if(items instanceof Map)
		{
			Map map=(Map) items;
			collection=map.entrySet();
		}
		else if(items instanceof Collection)
		{
			collection=(Collection) items;		
		}
		else if(items instanceof Object[])
		{
			Object[]objs=(Object[]) items;
			collection=Arrays.asList(objs);
		}
		else if(items.getClass().isArray())
		{
			int length=Array.getLength(items);
			collection=new ArrayList();
			for(int i=0;i<length;++i)
			{
				collection.add(Array.get(items, i));
			}
		}
		
		Iterator it=collection.iterator();
		while(it.hasNext())
		{
			Object ob=it.next();
			this.getJspContext().setAttribute(var, ob);
			getJspBody().invoke(null);
		}
	}
}


<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
        "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>debug</short-name>
  <uri>http://www.forEach.com</uri>


   <tag>
    <name>forEach</name>
    <tag-class>com.example.ForEach</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
   		 <name>items</name>
   		 <required>true</required>
   		 <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
   		 <name>var</name>
   		 <required>true</required>
   		 <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
  
</taglib>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.forEach.com"  prefix="wan" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'ForEach.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <%
   		Map map=new HashMap();
   		map.put("aaa", "111");
	 	map.put("bbb", "222");   
	 	request.setAttribute("map", map);	
	 	
	 	Integer numbers[]={1,2,3};
	 	request.setAttribute("numbers", numbers);
	 	
	 	List list=new ArrayList();
	 	list.add(11);   
	 	list.add(22);	
	 	request.setAttribute("list", list);
	 	
	 	int nums[]={4,5,6};
	 	request.setAttribute("nums", nums);	 	
   %>
   -----------------map------------------------<br/>
   <wan:forEach var="entry" items="${map}">
    ${entry.key}:${entry.value}
   </wan:forEach>
   <br/>
   ----------------numbers----------------------<br/>
   <wan:forEach var="index" items="${numbers}">
    ${index}
   </wan:forEach>
   <br/>
   ----------------list-------------------------------<br/>
   <wan:forEach var="index" items="${list}">
    ${index}
   </wan:forEach>
   <br/>
   ----------------nums-----------------------------------<br/>
   <wan:forEach var="index" items="${nums}">
    ${index}
   </wan:forEach>

  </body>
</html>














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值