日期:2014-05-16  浏览次数:20399 次

jsp开发迭代标签二
该例注意实现对不同集合的迭代

看例子

第一步:编写标签处理器类
public class ForeachTag2 extends SimpleTagSupport {

private Object items;
private String var;
//把所有的集合和数组转换成单列集合
private Collection collection;


public void setVar(String var) {
this.var = var;
}

public void setCollection(Collection collection) {
this.collection = collection;
}

public void setItems(Object items) {
this.items = items;

if(items==null)
collection=null;
//双列集合
if(items instanceof Collection)
{
collection=(Collection) items;
}
//单列集合
if(items instanceof Map){
Map map=(Map)items;
collection=map.entrySet();
}
//数组 不能用instanceof 因为如果是基本数据类型就会报错
if(items.getClass().isArray()){
this.collection=new ArrayList();
int len=Array.getLength(items);
for(int i=0;i<len;i++)
this.collection.add(Array.get(items, i));
}

}

public void doTag() throws JspException, IOException {

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

第二步:编写标签描述文件



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

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>SimpleTagLibrary</short-name>
    <uri>http://www.liyong.foreach1tag</uri>
   <tag>
   <tag>
    <name>foreach2</name>
    <tag-class>com.liyong.foreach.ForeachTag2</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>

第三步:编写jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.liyong.foreach1tag" prefix="foreach"%>
<%
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 'foreach1.jsp' starting page</title>

<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>
 
  <body>&nbsp;<br>

<foreach:foreach2 items="${list}" var="str">
${str }<br/>
&l