Spring4 + Thymeleaf3表单验证:bean名称#fields在模板中不可用

时间:2017-02-14 05:26:35

标签: spring spring-mvc spring-boot thymeleaf

当我尝试在表单模板中显示验证错误时,我在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";
}

请告诉我错误的位置。

1 个答案:

答案 0 :(得分:0)

您为表单元素div中的错误设置了错误的值。 th:错误应包含字段名称。用以下内容更新您的表单:

    <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>
相关问题