我是 Thymeleaf 新手,正在尝试检查模板中的 null 属性
<form th:action="@{/saveUser/__${user.id}__}" th:object="${user}" method="post">
如果我正在编辑已定义 id 的现有用户,则表单提交正常,但是使用相同的表单添加新用户,我会得到以下结果
HTTP Status 400 - http://localhost:8080/myApp/saveUser/null"
我的 Controller :
@RequestMapping(value = "/saveUser/{id}", method = RequestMethod.POST)
public String saveUser(@ModelAttribute("user") User user, @PathVariable Long id, Model model) {
model.addAttribute("user", user);
userRepo.save(user); //JPA Repo
return "success";
}
我的想法是,如果我可以检查空 ID,我可以以某种方式插入一个唯一的 ID。更好的是,如果我可以利用在我的 User 对象的 ID 上设置的 @GeneratedValue
那么我想我会处于良好状态
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
编辑包括我的用户编辑表单方法,该方法返回相同的表单,但预先填充了用户的模型属性
@RequestMapping(value = "/edit/user/{id}", method = RequestMethod.GET)
public ModelAndView getUserEditForm(@PathVariable Long id, Model model){
ModelAndView mav = new ModelAndView("userForm");
User user = userRepo.findOne(id);
mav.addObject("userForm", user);
return mav;
}
编辑 2 包括我的整个表单(ID 对用户“隐藏”)
<form th:action="@{/saveUser/__${user.id}__}" th:object="${user}" method="post">
<input id="id" type="hidden" th:field="*{id}" />
<input id="id" type="text" th:field="*{name}" />
<input id="id" type="text" th:field="*{address}" />
<button id="save">Save</button>
</form>
最佳答案
根据讨论,假设您调用以下方法来填充用户对象,因此表单在提交时失败:
@RequestMapping(value = "/saveUser/{id}", method = RequestMethod.POST)
public String saveUser(@ModelAttribute("user") User user, @PathVariable Long id, Model model) {
model.addAttribute("user", user);
userRepo.save(user); //JPA Repo
return "success";
}
该方法不起作用的原因是您可能首先传递一个空的用户对象。 要修复此问题,您需要在调用页面之前实现检查以确保对象不为 null。
一种解决方案可能是:
@RequestMapping(value = "/saveUser/{id}", method = RequestMethod.POST)
public String saveUser(@ModelAttribute("user") User user, @PathVariable Long id, Model model) {
userRepo.save(user); //JPA Repo
if(user == null) // check if user object is empty
user = new User(); // if user is empty, then instantiate a new user object
model.addAttribute("user", user);
return "success";
}
以上内容将确保当您将用户对象传递给模型时,它始终可用。
关于java - 检查 Thymeleaf 模板中的 Null 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31040609/