[英]Spring4 + Thymeleaf3 Form Validation : bean name #fields not available in templates
当我尝试在表单模板中显示验证错误时,在spring4 + thymeleaf3应用程序中出现以下错误。
Neither BindingResult nor plain target object for bean name '#fields' available as request attribute
我的表格如下。
<form th:action="@{/user/save}" method="post" th:object="${user}">
<ul th:if="${#fields.hasErrors()}">
<li th:each="err : ${#fields.errors('*')}" th:text="${err}"></li>
</ul>
<div>
<label>Name</label>
<div>
<input type="text" th:field="*{firstName}" placeholder="First Name">
<input type="text" th:field="*{lastName}" placeholder="Last Name">
<div th:if="${#fields.hasErrors('firstName')}" th:errors="${#fields.errors('firstName')}"></div>
<div th:if="${#fields.hasErrors('lastName')}" th:errors="${#fields.errors('lastName')}"></div>
</div>
</div>...
该表单可以很好地呈现给以下get请求映射。
@GetMapping("/create")
public String create(ModelMap model) {
model.put("user", new User());
return VIEW_DIR.concat("form");
}
但是,当将表单与某些无效字段一起提交给以下方法时,它将产生上述错误。
@PostMapping("/save")
public String save(@Valid User user, BindingResult bindingResult, ModelMap model) {
if(bindingResult.hasErrors()) {
return VIEW_DIR.concat("form");
}
userService.save(user);
return "redirect:list";
}
您能告诉我错误在哪里吗?
您为表单元素div中的th:error设置了错误的值。 th:errors应该包含字段名称。 使用以下方法更新您的表单:
<div>
<input type="text" th:field="*{firstName}" placeholder="First Name">
<input type="text" th:field="*{lastName}" placeholder="Last Name">
<div th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"></div>
<div th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}"></div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.