Spring4&x2B;Thymeleaf3表单验证:bean name#字段在模板中不可用
当我试图在表单模板中显示验证错误时,我在spring4+TelymeleAF3应用程序中遇到以下错误Spring4&x2B;Thymeleaf3表单验证:bean name#字段在模板中不可用,spring,spring-mvc,spring-boot,thymeleaf,Spring,Spring Mvc,Spring Boot,Thymeleaf,当我试图在表单模板中显示验证错误时,我在spring4+TelymeleAF3应用程序中遇到以下错误 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="$
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>...
但是当表单与一些无效字段一起提交给下面的方法时,会出现上述错误
@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:errors设置了错误的值。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>
<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>