【问题标题】:Switch Statement / Iteration in JSTL using Custom Tags Collection使用自定义标签集合在 JSTL 中切换语句/迭代
【发布时间】:2012-03-02 08:09:40
【问题描述】:

HelloTag.Java

public class HelloTag extends SimpleTagSupport {

@Override
public void doTag() throws JspException, IOException {
    JspWriter out = getJspContext().getOut();

    ArrayList outerList = new ArrayList();
    ArrayList innerList = null;
    for (int i = 0; i < 5; i++) {
        innerList = new ArrayList();
        innerList.add("1");
        innerList.add("Name");
        outerList.add(innerList);
    }
    for (int i = 0; i < outerList.size(); i++) {
        for (int j = 0; j < innerList.size(); j++) {
            out.println(innerList.get(j));
        }
    }
}
}

在 JSP 文件中, 有如下代码sn-p:

 <body>
    <ct:Hello></ct:Hello>
</body>

当我运行 JSP 文件时,这个文件显示了准确的结果;但是

我想决定来自自定义标记类的每个值

比如

 <c:set var="name" scope="" value=""/>
 <c:choose>
 <c:when test="${name == 1}">
  This is Your ID:-
 </c:when>
 <c:otherwise>
    This is Your Name
 </c:otherwise>
 </c:choose>

上面的代码只是为了举例。请更新我如何决定来自自定义标签类的每个值。

解释我的问题的另一种方法是,我想将每个值存储在一个变量中,然后只使用没有 Scriplet 标签的 JSTL 就该值做出决定,专注于上述场景(HelloTag.Java强>)

【问题讨论】:

  • 据我所知,SimpleTagSupport 不允许你拥有 JSP 正文内容,如果你正在实现类似于 的东西,那么你需要使用 BodyTagSupport
  • 亲爱的@Dapeng,我会很感激用一个例子来解决这个问题

标签: java jsp jakarta-ee jstl


【解决方案1】:

真的不清楚你在问什么。但是您的标签实际上只是循环遍历外部列表的每个内部列表(嗯,事实上,我想它应该这样做,但它有一个错误,所以它没有)。

您不需要自定义标记来执行此操作,因为 JSTL &lt;c:forEach&gt; 标记已经执行此操作。假设您在请求(或页面、会话或应用程序)属性中存储了一个 outerList:

<%-- iterate through the outer list --%>
<c:forEach var="innerList" items="${outerList}">
    <%-- iterate through the innerList --%>
    <c:forEach var="element" items="${innerList}">
        <%-- do what you want with the element --%>
    </c:forEach>
</c:forEach>

从您的问题来看,在我看来,您不应该有一个内部列表。相反,外部列表应该包含具有getId()getName() 方法的对象(例如Person 类的实例)。因此,循环将是:

<%-- iterate through the outer list --%>
<c:forEach var="person" items="${personList}">
    ID : ${person.id}<br/>
    Name : <c:out value="${person.name}"/>
</c:forEach>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多