Reputation: 189
Is it possible to display a variable-length list (or set) of Strings in a JSP page using the Spring framework ?
Currently I have the following in my Java Controller :-
@Controller
@RequestMapping("/")
public class HelloController
{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model)
{
model.addAttribute("message1", "Cat");
model.addAttribute("message2", "Dog");
model.addAttribute("message3", "Fish");
model.addAttribute("message4", "Bird");
return "hello";
}
}
Currently I have the following in "hello.jsp" :-
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>${message1}</p>
<p>${message2}</p>
<p>${message3}</p>
<p>${message4}</p>
</body>
</html>
Is it possible to do this but with a variable-length list (or set) ?
Thank you for your time,
James
Upvotes: 0
Views: 890
Reputation: 437
Put your key and value pair into Map and set it into model object.
Iterate Map object using jstl foreach loop in jsp page and get required output in key value pait
(1)Write your Controller
Map<String, String> messageList = new HashMap<String, String>();
messageList.put("message1", "Cat");
messageList.put("message2", "value2");
messageList.put("message3", "value3");
messageList.put("message4", "value4");
model.addAttribute("messageList",messageList);
(2)JSP page
<c:forEach var="msg" items="${messageList}">
${msg.key} : ${msg.value}
</c:forEach>
Upvotes: 1
Reputation: 159106
Put a List
object into the model, and use a <c:forEach>
loop to iterate the list.
model.addAttribute("messages", Arrays.asList("Cat", "Dog", "Fish", "Bird"));
<c:forEach var="message" items="${messages}">
<p>${message}</p>
</c:forEach>
Upvotes: 1