【问题标题】:Spring4 + Thymeleaf3 Form Validation : bean name #fields not available in templatesSpring + Thymeleaf 表单验证:bean name #fields 在模板中不可用
【发布时间】:2017-02-14 05:26:34
【问题描述】:

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

表单为以下获取请求映射很好地呈现。

@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";
}

你能告诉我错误在哪里吗?

【问题讨论】:

    标签: spring spring-mvc spring-boot thymeleaf


    【解决方案1】:

    您在表单元素 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2017-11-28
      • 2019-12-26
      • 1970-01-01
      • 2020-09-18
      • 2020-06-09
      • 2017-10-30
      相关资源
      最近更新 更多