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

Spring Thymeleaf视图向Controller传值失败,接收空值求助

问题:Thymeleaf模板向Controller传递数据时,FechaInicioFinal对象始终为空

在尝试将Thymeleaf模板中的日期数据传递到Spring Controller时,FechaInicioFinal对象始终接收空值,相关代码如下:

Thymeleaf模板代码

<form action="#" th:action="@{/pacientes/fechas}" th:object="${fechaInicioFinal}" method="GET">
    <table>
        <tr>
            <td><label>Fecha Inicio :</label></td>
            <td><input type="datetime-local" th:field="*{fechaInicio}"></td>
        </tr>
        <tr>
            <td><label>Fecha final :</label></td>
            <td><input type="datetime-local" th:field="*{fechaFinal}"></td>
        </tr>
    </table>
    <input type="submit" value="Buscar">
</form>

接收请求的Controller代码

@GetMapping("/fechas")
public String buscarFechas(@ModelAttribute FechaInicioFinal fechaInicioFinal, BindingResult result, Model model,
        RedirectAttributes redirectAttrs) {
    LOG.info(fechaInicioFinal.toString()); // 此处获取到空值
    // 业务逻辑
}

渲染模板的Controller代码

@GetMapping("/buscarFechas")
public String obtenerFechas(Model model, FechaInicioFinal fechaInicioFinal) {
    model.addAttribute("fechaInicioFinal", fechaInicioFinal);
    return "p_buscar_fechas";
}

已参考Spring MVC数据传递教程及同类问题,未解决问题。


解决步骤

  1. 确保FechaInicioFinal类配置正确

    • 类必须包含fechaInicio、fechaFinal属性,且提供标准的getter/setter方法——Spring MVC依赖这些方法完成数据绑定。
    • 由于datetime-local输入框传递ISO格式字符串(如2024-05-20T14:30),需为属性添加日期格式化注解,指定匹配的格式:
      public class FechaInicioFinal {
          @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
          private LocalDateTime fechaInicio;
          
          @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
          private LocalDateTime fechaFinal;
      
          // 此处添加getter和setter方法
      }
      
  2. 修正渲染模板的Controller逻辑

    • 当前obtenerFechas方法直接将参数中的空FechaInicioFinal对象传入Model,建议手动实例化后添加,避免绑定异常:
      @GetMapping("/buscarFechas")
      public String obtenerFechas(Model model) {
          model.addAttribute("fechaInicioFinal", new FechaInicioFinal());
          return "p_buscar_fechas";
      }
      
  3. 检查请求参数与提交方式

    • 打开浏览器开发者工具,查看表单提交时的请求参数,确认参数名是fechaInicio和fechaFinal(与类属性名一致)。
    • 若GET方式绑定仍有问题,可尝试将表单method改为POST,同时Controller对应改为@PostMapping("/fechas")——POST请求的参数绑定逻辑更稳定,适合表单数据提交。
  4. 手动指定表单参数名(备选方案)

    • 若th:field生成的参数名不符合预期,可直接手动指定name属性替代th:field:
      <input type="datetime-local" name="fechaInicio" th:value="${fechaInicioFinal.fechaInicio}">
      <input type="datetime-local" name="fechaFinal" th:value="${fechaInicioFinal.fechaFinal}">
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:27:32