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);
            }
        }
    }
  • 相关阅读:
    FreeMarker缓存处理
    freemarker入门实例与源码研究准备工作
    Freemarker常用技巧(二)
    Freemarker常用技巧(一)
    Hessian与Spring整合
    Hessian学习
    数组常见的面试题
    关于排序的实现
    Redis与Memcache的区别
    JDBC编程步骤
  • 原文地址:https://www.cnblogs.com/Westfalen/p/5978818.html
Copyright © 2011-2022 走看看