0

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

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.