可以将模型传递给 Spring,但 Thymeleaf 仍然指示错误



我的问题是我可以在Thymeleaf和Spring之间传递模型,但Thymeleaf仍然指示错误。

弹簧代码:

@GetMapping("{id}/edit")
  String getEdit(@PathVariable Long id, Model model) {
  postRepository.findById(id).ifPresent(o -> model.addAttribute("post", o));
  return "edit";
}
@PostMapping("{id}/edit")
  String postEdit(@ModelAttribute Post post) {
  postRepository.save(post);
  return "redirect:/";
}

百里香叶代码:

<form th:action="|/${post.id}/edit|" th:method="POST" th:object="${post}">
  <input type="text" th:value="*{title}" name="title">
  <input type="text" th:value="*{content}" name="content">
  <input type="submit" value="Edit">
</form>

Thymeleaf 表示它无法解析 ${post.id}、*{title} 和 *{content}。我已经停止并重新运行该应用程序更多次,所以我认为我的代码中有些问题,即使它有效。

我应该怎么做才能解决这个问题?

首先,我认为您在帖子映射中不需要路径变量。您可以使用不带路径变量的发布映射。因此,请尝试像修改控制器一样

@PostMapping("/edit")
  String postEdit(@ModelAttribute Post post) {
  postRepository.save(post);
  return "redirect:/";
}

如果你像这样编写控制器,那么在百里香叶中定义路径将很容易。

第二个错误can't resolve *{title} and *{content}是因为无效的关键字。请尝试修改您的百里香叶

<form th:action="@{/edit}" th:method="POST" th:object="${post}">
  <input type="text" th:field="*{title}" name="title">
  <input type="text" th:field="*{content}" name="content">
  <input type="submit" value="Edit">
</form>

我认为这将如您所期望的那样工作。

最新更新