Spring中如何通过JSTL将数组型Map所有元素传递至JSP并完整展示
解决Spring控制器传递气象预报数组到JSP仅显示最后一条的问题
问题根源
你循环时复用了同一个Map对象,Java里对象是引用传递,每次循环修改的都是同一个Map的内容,最后存入List的全是这个Map的引用,自然只会显示最后一次修改的结果。
修正步骤
1. 调整控制器代码
把Map的创建移到循环内部,每次循环都生成新的Map实例,确保每个周期数据都存在独立的Map里:
// 假设你已经用ObjectMapper解析出了periods数组(JsonNode类型) List<Map<String, Object>> periodsList = new ArrayList<>(); for (JsonNode periodNode : periodsArray) { // 每次循环新建Map,避免引用复用 Map<String, Object> periodMap = new HashMap<>(); // 映射你需要的字段,比如日期、温度、天气描述等 periodMap.put("forecastDate", periodNode.get("date").asText()); periodMap.put("temperature", periodNode.get("temperature").asInt()); periodMap.put("weatherDesc", periodNode.get("description").asText()); // 把当前周期的Map加入List periodsList.add(periodMap); } // 将整个List传递给JSP model.addAttribute("weatherPeriods", periodsList);
2. 确认JSP的遍历代码正确
确保JSTL的<c:forEach>标签正确遍历你传递的List:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <div class="weather-forecast"> <h3>未来气象预报</h3> <ul> <c:forEach items="${weatherPeriods}" var="period"> <li> <span>日期:${period.forecastDate}</span> <span>温度:${period.temperature}℃</span> <span>天气:${period.weatherDesc}</span> </li> </c:forEach> </ul> </div>
额外建议
如果气象预报的字段固定,建议创建一个实体类(比如WeatherPeriod)来代替Map,这样代码可读性更强,也不容易出错:
public class WeatherPeriod { private String forecastDate; private Integer temperature; private String weatherDesc; // 生成getter、setter方法 }
然后控制器里循环解析成List<WeatherPeriod>,JSP里直接用${period.forecastDate}这样的方式取值,代码更规范。
内容的提问来源于stack exchange,提问作者Khanh Luong Van
相关产品推荐
相关产品推荐

