我的 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标签,然后引用每个项目的 key
和 value
字段。
<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/