java Thymeleaf Form传递null对象

3npbholx  于 4个月前  发布在  Java
关注(0)|答案(1)|浏览(58)

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


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

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


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



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

b5buobof

b5buobof1#

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

相关问题