簡體   English   中英

使用Spring框架在JSP頁面中顯示字符串的變長列表

[英]Display variable-length list of Strings in JSP page using Spring framework

是否可以使用Spring框架在JSP頁面中顯示可變長度的字符串列表(或集合)?

目前,我的Java控制器中具有以下內容:

@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";
   }
}

目前,我在“ 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>

可以使用可變長度列表(或集合)來執行此操作嗎?

感謝您的時間,

詹姆士

List對象放入模型中,並使用<c:forEach>循環迭代列表。

model.addAttribute("messages", Arrays.asList("Cat", "Dog", "Fish", "Bird"));
<c:forEach var="message" items="${messages}">
  <p>${message}</p>
</c:forEach>

將您的鍵和值對放入Map中並將其設置為模型對象。

在jsp頁面中使用jstl foreach循環迭代Map對象,並在鍵值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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM