java - 如何在 JSP 中循环访问 Spring HashMap 模型中存储的键和值?

标签 java jsp spring-mvc jstl

我的 Spring Controller 中有一个方法:

public ModelAndView testRoCompliance(@RequestParam String regOfficeStr) {
    Map<String, Object> results = new HashMap<>();
    results.put("inputs", "an input");
    results.put("result", "the answer");
    ModelAndView modelAndView = new ModelAndView("simpleOutput", results);
    return modelAndView;
}

我有一个可以打印变量的 JSP:

<body>
Inputs: ${inputs}
<br/>
Result: ${result}
</body>

如何不显式列出变量,而是循环遍历 结果 HashMap 的键和值?

最佳答案

使用c:forEach标签,然后引用每个项目的 keyvalue 字段。

<c:forEach var="result" items="${results}">
   Key: ${result.key}
   Value: ${result.value}
</c:forEach>

这需要更改您的 Controller :

 public ModelAndView testRoCompliance(@RequestParam String regOfficeStr) {
    Map<String, Object> results = new HashMap<>();
    results.put("inputs", "an input");
    results.put("result", "the answer");
    ModelAndView modelAndView = new ModelAndView("simpleOutput");
    modelAndView.addObject("results", results);
    return modelAndView;  
 }

关于java - 如何在 JSP 中循环访问 Spring HashMap 模型中存储的键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20671908/

相关文章:

java - 下载完成后自动打开文件PDF

spring - 如何将 "a-b"查询映射到 Spring MVC 中的命令对象

java - Spring portlet 中的 @GetMapping 注释

java - 使用 gradle bootJar 而不是 jar 任务并且在 Jenkins 中构建失败

java - java遍历框架中的neo4j cypher查询

jsp - EL 和 Scriptlet 如何获取 pageContext.getAttribute 子项?

java - TeamCity:此处不允许使用脚本元素 jsp:declaration、jsp:expression、jsp:scriptlet

java - 启动应用程序之前远程数据库的 Spring 端口转发

java - Android运行时: FATAL EXCEPTION: main Process data parcel size 1245464 bytes error

java - ${pageContext.request.contextPath} 和 request.getContextPath() 有什么区别