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);
            }
        }
    }
  • 相关阅读:
    记一次大数据量后台服务的性能优化(转载)
    javascript void(0)
    IE11浏览器设置为兼容不同IE版本
    Asp.net WebForm(4) Server对象、跳转分析、验证控件和站点导航
    http请求错误码(转载)
    windows系统和IE的兼容性问题
    Lombok常用注解
    Typora配置图床PicGo,使用阿里云Oss 存储
    Picgo +sm.ms打造免费图床个人工具
    OSS —— 对象存储介绍
  • 原文地址:https://www.cnblogs.com/Westfalen/p/5978818.html
Copyright © 2011-2022 走看看