zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
  • 相关阅读:
    vs2019编译错误:Exception Processing Message 0xc0000005 Parameters...
    error LNK2001
    Debug Assertion Failed
    对路径“………………”的访问被拒绝
    c语言打开文件为什么总是以二进制方式打开
    关于typedef的用法总结
    xml学习第一天
    关于VS2017编译成功系统找不到指定文件.exe的问题
    引入的外部js文件在html文件在浏览器中乱码显示
    结对作业(四则运算)
  • 原文地址:https://www.cnblogs.com/Westfalen/p/5978818.html
Copyright © 2011-2022 走看看