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

可以将模型传递给Spring,但Thymeleaf仍然指示错误,spring,thymeleaf,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("

我的问题是我可以在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:/";
}
Thymeleaf代码:

<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}。我已经停止并重新运行了应用程序更多次,因此我认为我的代码中存在一些错误,即使它可以工作


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

首先,我认为在post映射中不需要path变量。可以使用不带路径变量的post映射。所以试着像这样修改你的控制器

@PostMapping("/edit")
  String postEdit(@ModelAttribute Post post) {
  postRepository.save(post);
  return "redirect:/";
}
如果您像这样编写控制器,那么在thymeleaf中定义路径就很容易了

第二个错误
无法解析*{title}和*{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>

我想这会像你期望的那样起作用