【问题标题】:Input fields are showing blank in Thymeleaf Spring MVCThymeleaf Spring MVC 中的输入字段显示为空白
【发布时间】:2023-03-18 03:06:01
【问题描述】:

我正在尝试使用 springMvc 和 thymeleaf 创建一个编辑表单。输入字段未填充从控制器返回的值。

控制器:

@RequestMapping(value = "updatecustomer")
public String search(@ModelAttribute("customerDto") CustomerDto customerDto, Model model) {
    Customer customer = service.search(customerDto);
    model.addAttribute("customer", customer);
    return "mypage";
}

表格:

<form method="post" th:action="@{updatecustomer}" th:object="${customerDto}">
    <label>Email: </label><input type="text" th:field="*{email}" />
    <input type="submit" />
</form>

在浏览器上生成的 html:

<input type="text" id="email" name="email" value="">

调试显示值存在于控制器中并返回查看,但电子邮件输入值为空白。

请指教。

【问题讨论】:

    标签: java html spring spring-mvc thymeleaf


    【解决方案1】:

    在您的 Thymeleaf 代码中,您将 customerDto 绑定到表单

    th:object="${customerDto}"
    

    在您的控制器中,您将客户数据传递给 customer 属性名称

    model.addAttribute("customer", customer);
    

    你应该匹配这两个。例如,将您的 Thymeleaf 代码更改为此

    th:object="${customer}"
    

    【讨论】:

    • 因为@ModelAttribute("customerDto") 我认为他可以使用 th:object="${customerDto}"
    【解决方案2】:

    也许您应该在您的 JSP 中映射模型中的实体“客户”,并使用它自己的字段!

    <label>Email: </label><input type="text" th:field="*{customer.email}" />
    

    试试并告诉我们!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多