0

In my controller I add to model dynamically called attributes, like:

model.addAttribute("message"+singleMessage.getId()+"comments", messageComments);

so in my jsp view I have collections like message1comments, message7comments, message457comments etc.

Now when I go through messages collection when I'm displaying a message with id let's say 19 I want to check if it has any comments by checking if such attribute/collection like "message19comments" exists.

Question is: how to do it? I don't know how to construct such a name and check if argument with this name exists. I tried:

<c:if test="${not empty "message"+message.id+"comments"}>

and some other things but to no avail. When I print

${requestScope}

I can see all those comment collections. But how do I check if the one with dynamically generated name exists?

Witcher
  • 41
  • 6
  • 3
    This is unclear, and the idea of dynamically generating attribute names like that could be an anti-pattern... but it's hard to tell given what you've posted. It sounds like you might need to use a real data structure instead of building string keys like that. – Jim Garrison Jun 30 '18 at 02:44
  • 1
    Put a Map> in your model, so you can get easily the list of comments for a message. – Robert Hume Jun 30 '18 at 07:00

1 Answers1

1

A Map<messageId, listOfComments> would allow you to easily recall the list of comments associated with any message by supplying the message ID, so you can try to put a Map in your model as in the following code example (adjust it with your data types):

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);

Then, in the JSP you can recall the list of comments uning the message ID:

<c:if test="${not empty commentMap[YOUR_MESSAGE_ID_HERE]}>

See also Get value from hashmap based on key to JSTL for further information.

Robert Hume
  • 1,129
  • 2
  • 14
  • 25