Thymeleaf无法渲染List值,Spring MVC提交后表格无数据展示
问题根因
你当前的问题核心是getLocationsByDate接口使用了重定向逻辑:return "redirect:/sightings"。重定向属于客户端两次独立请求,第一次请求中存入Model的locations会随着请求结束销毁,第二次跳转访问/sightings对应的displayLocations方法没有向Model中存入locations数据,所以Thymeleaf渲染时读取不到对应值,表格自然无内容。
解决方案
提供两种常用的修复方案,可根据你的业务需求选择:
方案1:将重定向改为服务端转发
直接返回视图名,复用当前请求的Model数据,修改getLocationsByDate返回值即可:
@GetMapping("getLocationsByDate") public String getLocationsByDate(HttpServletRequest request,Model model) { String date =request.getParameter("chooseDate"); LocalDate localDate = LocalDate.parse(date); List<Location> locations = locationDao.sightingsOnDate(localDate); model.addAttribute("locations",locations); // 去掉redirect前缀,直接返回视图名,服务端内部跳转,保留Model数据 return "sightings"; }
注意:该方案提交表单后地址栏会显示
/getLocationsByDate,用户刷新页面会重复提交表单请求。
方案2:使用RedirectAttributes传递重定向参数
如果需要保留地址栏为/sightings、避免重复提交,使用Flash属性传递参数,重定向后数据仍然可用:
@GetMapping("getLocationsByDate") public String getLocationsByDate(HttpServletRequest request, RedirectAttributes attr) { String date =request.getParameter("chooseDate"); LocalDate localDate = LocalDate.parse(date); List<Location> locations = locationDao.sightingsOnDate(localDate); // 用flash属性存值,重定向后自动注入到目标请求的Model中 attr.addFlashAttribute("locations",locations); return "redirect:/sightings"; }
建议同时修改displayLocations方法,增加空值兼容,避免首次进入页面时Thymeleaf模板报错:
@GetMapping("sightings") public String displayLocations(Model model) { // 没有查询数据时默认传入空列表 if(!model.containsAttribute("locations")){ model.addAttribute("locations", Collections.emptyList()); } return "sightings"; }
其他验证点
你提供的Location实体类的getter方法均为public、Thymeleaf命名空间、属性渲染语法均无问题,修改上述逻辑后即可正常渲染列表。
内容的提问来源于stack exchange,提问作者JmanxC
相关产品推荐
相关产品推荐

