【问题标题】:Display variable-length list of Strings in JSP page using Spring framework使用 Spring 框架在 JSP 页面中显示可变长度的字符串列表
【发布时间】:2015-11-05 01:06:49
【问题描述】:

是否可以使用 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>

是否可以使用可变长度列表(或集合)来执行此操作?

感谢您的宝贵时间,

詹姆斯

【问题讨论】:

    标签: java spring jsp spring-mvc tomcat


    【解决方案1】:

    List 对象放入模型中,并使用&lt;c:forEach&gt; 循环迭代列表。

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

    【讨论】:

      【解决方案2】:

      将您的键值对放入 Map 并将其设置为模型对象。

      在jsp页面中使用jstl foreach循环迭代Map对象,并在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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 2012-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多