我对 Spring Web 和 Thymeleaf 很陌生,我正在尝试创建一个表单,将 Todo 对象传递给控制器,控制器将该对象保存到数据库中。表单接受输入,但传递给 post 方法的实际对象全部为 null 和默认值。我在堆栈溢出上发现了类似的问题,但似乎没有一个解决方案适用。我是不是错过了什么?
TodoController.java:
@Controller
@RequestMapping("/todos")
public class TodoController {
@Autowired
TodoRepository todoRepository;
@GetMapping
public String getAllTodos(Model model, @ModelAttribute Todo todo) {
List<Todo> todos = todoRepository.findAll();
model.addAttribute("todos", todos);
model.addAttribute("todo", new Todo());
return "test";
}
@PostMapping("/post")
public String addUser(Model model, @ModelAttribute("todo") Todo todo) {
System.out.println("POST!!!!!!!!!!!!!!! : " + todo.toString());
todoRepository.save(todo);
return "redirect:/";
}
}
test.html 中的表单元素:
<form method="post" th:action="@{/todos/post}" th:object="${todo}">
<label for="name">Name</label>
<input id="name" placeholder="Enter Name" required type="text" th:field="*{name}"/>
<label for="description">Description</label>
<input id="description" placeholder="Enter Description" required type="text" th:field="*{description}"/>
<input type="submit" value="Create Todo">
</form>
Todo.java:
public record Todo(@Id Long id, Long userId, String name, String description, boolean completed) {
public Todo() {
this(null, null, "","", false);
}
}
当我输入一个包含名称和描述值的对象时,终端打印出一个仅包含 null 和默认值(空字符串)的对象:
POST!!!!!!!!!!!!!!! : Todo[id=null, userId=null, name=, description=, completed=false]
并成功将该对象保存到数据库中:
之前:
之后:
问题似乎要么是表单、表单和端点之间的连接,要么是使用记录的一些复杂性。除此之外,我被困住了。
提前致谢! :)
@Chetan Ahetao 明白了。记录是不可变的。必须使用带有实体注释的常规类。