在循环JSTL中动态创建变量 [英] Create variables dynamically in loop JSTL

查看:188
本文介绍了在循环JSTL中动态创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Servlet请求中检索带有某些数组的HashMap,它们的名称分别为Items1,Items2,ItemsN.我永远不会确切地知道HashMap的大小,所以我想使用<c:set/>标记来迭代<c:forEach/>循环来创建变量,因为我不想像这样手动创建它们:

I am retrieving a HashMap from a servlet request with some arrays, their names would be Items1, Items2, ItemsN. I'll never know the HashMap size exactly, so I want to create variables with <c:set/> tag iterating a <c:forEach/> loop because I don't want to create them manually like this:

<c:set var="listItems1" value="${Map['Items1']}" scope="session"/>
<c:set var="listItems2" value="${Map['Items2']}" scope="session"/>
<c:set var="listItems3" value="${Map['Items3']}" scope="session"/>
<c:set var="listItems4" value="${Map['Items4']}" scope="session"/>
<c:set var="listItems5" value="${Map['Items5']}" scope="session"/>

相反,我想以这种方式创建它们:

Instead of that I want to create them in this way:

<c:forEach items="${Map['Items']}" var="Items" varStatus="i">
     <c:set var="${listItems + i.index}" value="${Items}"/>
</c:forEach>

但是我不能因为JSTL告诉我

But I can't because JSTL tells me

根据标签文件中的TLD或属性指令,属性var不接受任何表达式

According to TLD or attribute directive in tag file, attribute var does not accept any expressions

然后,我想知道是否可以在JSTL中动态创建变量,或者我必须手动创建它们

Then, I was wondering if is it possible create variables dynamically in JSTL or I have to create them manually

推荐答案

我永远不会确切知道HashMap的大小.

I'll never know the HashMap size exactly.

您可以使用jstl函数length来获取hashmap的长度,如下所示:

You can use jstl function length, to get length of hashmap as:

    Length of Map : ${fn:length(yourMap)}

请确保将其包含在jsp中:<%@ taglib prefix ="fn" uri ="http://java.sun.com/jsp/jstl/functions"%>

Make sure to include this in jsp: <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

如果您需要根据哈希图的大小进行迭代并执行某些操作,则可以尝试以下操作:

If you need to iterate based on size of hashmap and do something, you can try as:

    <c:forEach var="i" begin="1" end="${yourMap.size()}">
       //do something
    </c:forEach>

这篇关于在循环JSTL中动态创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆