javaWeb 使用jsp开发 foreach 标签

1.jsp代码

测试数据
<%
    List<String> list = new ArrayList<String>();
    list.add("aaa");
    list.add("bbb");
    list.add("ccc");
    request.setAttribute("list", list);
%>
<%
    int[] array = { 1, 3, 5 };
    request.setAttribute("array", array);
%>
调用foreach标签
<t:foreach var="i" items="${list }">    ${i }<br />    </t:foreach>
<t:foreach var="i" items="${array }">    ${i }<br />    </t:foreach>

2.tld文件代码

<tag>
        <name>foreach</name>
        <tag-class>de.bvb.web.tag.ForeachTag</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>

3.标签类代码

package de.bvb.web.tag;

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 String var;
    private Object items;
    private Collection collection;

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

    public void setItems(Object items) {
        this.items = items;
        if (items instanceof Collection) {
            collection = (Collection) items;
        }
        if (items instanceof Map) {
            collection = ((Map) items).entrySet();
        }
        if (items.getClass().isArray()) {
            this.collection = new ArrayList();
            int length = Array.getLength(items);
            for (int i = 0; i < length; i++) {
                collection.add(Array.get(items, i));
            }
        }
    }

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

 

posted @ 2016-10-19 21:35  MarcoReus  阅读(1472)  评论(0编辑  收藏  举报