java Thymeleaf Form传递null对象

3npbholx  于 2024-01-05  发布在  Java
关注(0)|答案(1)|浏览(300)

我是Spring Web和Thymeleaf的新手,我试图制作一个表单,它将Todo对象传递给控制器,控制器将该对象保存到数据库。表单接受输入,但传递给post方法的实际对象具有所有null和default值。我在堆栈溢出上发现了类似的问题,但似乎没有解决方案适用。我错过了什么吗?
TodoController.java:

  1. @Controller
  2. @RequestMapping("/todos")
  3. public class TodoController {
  4. @Autowired
  5. TodoRepository todoRepository;
  6. @GetMapping
  7. public String getAllTodos(Model model, @ModelAttribute Todo todo) {
  8. List<Todo> todos = todoRepository.findAll();
  9. model.addAttribute("todos", todos);
  10. model.addAttribute("todo", new Todo());
  11. return "test";
  12. }
  13. @PostMapping("/post")
  14. public String addUser(Model model, @ModelAttribute("todo") Todo todo) {
  15. System.out.println("POST!!!!!!!!!!!!!!! : " + todo.toString());
  16. todoRepository.save(todo);
  17. return "redirect:/";
  18. }
  19. }

字符串
来自test.html的表单元素:

  1. <form method="post" th:action="@{/todos/post}" th:object="${todo}">
  2. <label for="name">Name</label>
  3. <input id="name" placeholder="Enter Name" required type="text" th:field="*{name}"/>
  4. <label for="description">Description</label>
  5. <input id="description" placeholder="Enter Description" required type="text" th:field="*{description}"/>
  6. <input type="submit" value="Create Todo">
  7. </form>


Todo.java:

  1. public record Todo(@Id Long id, Long userId, String name, String description, boolean completed) {
  2. public Todo() {
  3. this(null, null, "","", false);
  4. }
  5. }


当我输入一个带有name和description值的对象时,终端会打印出一个只有null和default值(空字符串)的对象:

  1. POST!!!!!!!!!!!!!!! : Todo[id=null, userId=null, name=, description=, completed=false]


并成功地将该对象保存到数据库:
之前:
x1c 0d1x的数据
之后:



问题似乎是表单,表单和端点之间的连接,或者使用记录的一些复杂性。
提前感谢!:)

b5buobof

b5buobof1#

@Chetan Ahetao得到了它。记录是不可变的。必须使用带有Entity注解的常规类。

相关问题