【问题标题】:Why isn't the thymeleaf object recognized?为什么无法识别 thymeleaf 对象?
【发布时间】:2022-01-20 19:15:57
【问题描述】:

第一个被剪断的代码是我添加(或者更确切地说是尝试)在 html 中使用的属性“NewUser”。

'th:field="*{name}"' 弹出错误。

错误: 执行处理器“org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor”时出错

@RequestMapping("home")
public String newUser(Model model) {
    User newUser = new User();
    newUser.setId(100l);
    newUser.setName("Test");
    newUser.setEmail("test@what.com");
    newUser.setPermission(0);
    model.addAttribute(newUser);
    return "index";
}

<form action="#" th:action="@{/home/add}" th:object="${newUser}" method="get">
    <p>Id: <input type="text" th:field="*{name}" /></p>
    <p>Message: <input type="text" th:field="*{email}" /></p>
    <p>Message: <input type="text" th:field="*{permission}" /></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>

【问题讨论】:

  • 你可以尝试使用 th:object="${user}" 我相信当 Model.addAttribute 被调用时没有 attributeName 参数它使用小写类的名称
  • 遗憾的是它没有改变任何东西,同样的错误同一行。
  • 我同意 Josh Van de Walle 的观点。 Thymeleaf 找不到那个对象。要么你没有正确命名它(例如你应该这样做model.addAttribute("newUser", newUser);而不是model.addAttribute(newUser);)或者你在错误的控制器上并且根本没有添加对象。 See this (my code is the same as yours except I'm naming my attribute).

标签: spring-boot thymeleaf


【解决方案1】:

我认为原因是您没有为以下文件创建 getter 方法nameemailpermission 。因此,当thymeleaf 尝试呈现页面 时,它无法读取名称字段、电子邮件字段或权限字段的值

【讨论】:

  • 啊,我确实设置了 getter 方法,所以我想不是这样。
【解决方案2】:

我正在添加另一个模型,它似乎引起了问题,所以我最终这样做了,一切正常。

“userList”模型在代码的其他地方使用。

@GetMapping("home")
public String index(Model model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("userList", userService.getUsers());
    return "index";
}

<form th:object="${user}" th:action="@{/home/add}" method="get">
    <p>Id: <input type="text" th:field="*{name}" /></p>
    <p>Message: <input type="text" th:field="*{email}" /></p>
    <p>Message: <input type="text" th:field="*{permission}" /></p>
    <p><input type="submit" value="Submit" /> <input/></p>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    相关资源
    最近更新 更多