javaWeb 使用jsp开发 foreach 标签

本文介绍了一种在JSP中使用自定义foreach标签来遍历集合与数组的方法。通过编写特定的TLD文件及对应的标签处理类,实现了对不同类型的容器进行迭代并展示元素的功能。

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

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);
        }
    }
}

 

转载于:https://www.cnblogs.com/Westfalen/p/5978818.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值