You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot结合Thymeleaf表单提交后表格无数据问题咨询

问题原因

@PostMapping("/guardar") 接口在数据保存成功后,仅返回了lista-agendas视图名称,没有将列表查询结果listaAgendas塞入模型对象中,Thymeleaf渲染页面时找不到对应变量,因此表格无数据展示。
单独访问/lista-agendas时走了@GetMapping对应的接口,该接口内执行了列表查询逻辑并把结果塞入了模型,所以可以正常渲染。
同时直接返回视图名还存在重复提交的风险:用户在提交后刷新页面,会再次触发/guardar接口的保存逻辑。

解决方案

推荐使用重定向方案(符合POST接口最佳实践,避免重复提交),修改guardar方法的成功返回逻辑即可:

@PostMapping("/guardar")
public String guardar(ModelMap map, @RequestParam String nombre, @RequestParam String apellido,
                     @RequestParam Long telefono, @RequestParam String email,
                     @RequestParam String domicilio) {
    try {
        agendaService.crear(nombre, apellido, telefono, email, domicilio);
    } catch (AgendaException ex) {
        map.put("error", ex.getMessage());
        map.put("nombre", nombre);
        map.put("apellido", apellido);
        map.put("telefono", telefono);
        map.put("email", email);
        map.put("domicilio", domicilio);
        return "carga";
    }
    // 原返回逻辑改为重定向到列表接口,会自动执行GET接口的查询逻辑
    return "redirect:/lista-agendas";
}

如果不想用重定向,也可以在保存成功后手动塞入列表数据:

@PostMapping("/guardar")
public String guardar(ModelMap map, @RequestParam String nombre, @RequestParam String apellido,
                     @RequestParam Long telefono, @RequestParam String email,
                     @RequestParam String domicilio) {
    try {
        agendaService.crear(nombre, apellido, telefono, email, domicilio);
        // 手动查询列表并塞入模型
        List<Agenda> listaAgendas = agendaService.listaAgendas();
        map.put("listaAgendas", listaAgendas);
    } catch (AgendaException ex) {
        map.put("error", ex.getMessage());
        map.put("nombre", nombre);
        map.put("apellido", apellido);
        map.put("telefono", telefono);
        map.put("email", email);
        map.put("domicilio", domicilio);
        return "carga";
    }
    return "lista-agendas";
}

内容的提问来源于stack exchange,提问作者sixGdie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:06:04