在我的 Controller 中,我向模型添加动态调用的属性,例如:
model.addAttribute("message"+singleMessage.getId()+"comments", messageComments);
所以在我的 jsp View 中我有像 message1comments、message7comments、message457comments 等集合。
现在,当我显示一条 id 为 19 的消息时,我想通过检查消息集合是否存在“message19comments”等属性/集合来检查它是否有任何评论。
问题是:怎么做?我不知道如何构造这样的名称并检查具有该名称的参数是否存在。我尝试过:
<c:if test="${not empty "message"+message.id+"comments"}>
还有其他一些事情,但没有效果。当我打印时
${requestScope}
我可以看到所有这些评论集合。但如何检查动态生成的名称是否存在呢?
最佳答案
一个Map<messageId, listOfComments>
通过提供消息 ID,您可以轻松调用与任何消息关联的注释列表,因此您可以尝试将 Map 放入您的模型中,如以下代码示例所示(根据您的数据类型进行调整):
Map<Long, List<Comment>> commentMap = new HashMap<>();
for (Message singleMessage : messages) {
/* retrieve messageComments for this singleMessage here */
commentMap.put(singleMessage.getId(), messageComments);
}
model.addAttribute("commentMap", commentMap);
然后,在 JSP 中您可以通过消息 ID 调用评论列表:
<c:if test="${not empty commentMap[YOUR_MESSAGE_ID_HERE]}>
另请参阅Get value from hashmap based on key to JSTL欲了解更多信息。
关于java - 如何检查具有动态名称的参数/集合是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51111120/