【问题标题】:Thymeleaf Could not bind form errors using expression "*"Thymeleaf 无法使用表达式“*”绑定表单错误
【发布时间】:2017-10-19 22:16:36
【问题描述】:

我使用 Spring-boot 和 Thymeleaf 模板引擎,并尝试使用 th:classappend 属性为

使用 #fields.hasErrors('*') 表达式的 html 标签添加可选的“has-error”类
<form method="POST" action="/registration" class="form-signin">
        <h2 class="form-signin-heading">Create your account</h2>

        <div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''">
            <input name="username" type="text" class="form-control" placeholder="Username" autofocus="true"/>
            <p class="alert alert-danger" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></p>
        </div>

        <div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''">
            <input name="password" type="text" class="form-control" placeholder="Password" autofocus="true"/>
            <p class="alert alert-danger" th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></p>
        </div>

        <div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''">
            <input name="passwordConfirm" type="text" class="form-control" placeholder="Confirm your password" autofocus="true"/>
            <p class="alert alert-danger" th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}"></p>
        </div>

        <button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>


    </form>

但我有这个错误

无法使用表达式“*”绑定表单错误。请检查这个 表达式正在适当的上下文中执行(例如 带有 th:object 属性)

我的控制器方法

@RequestMapping(value = "/registration", method = RequestMethod.GET)
    public String registration(Model model) {
        model.addAttribute("userForm", new User());

        return "registration";
    }

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
        userValidator.validate(userForm, bindingResult);

        if (bindingResult.hasErrors()) {
            return "registration";
        }

        userService.save(userForm);

        securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());

        return "redirect:/welcome";
    }

我做错了什么?

【问题讨论】:

  • 答案已经在你得到的错误中`请检查这个表达式是否在适当的上下文中执行(例如,带有 th:object 属性). Your form element should contain a th:object="${userForm }"` 表达式,否则它不知道使用哪个命令对象。
  • @M.Deinum 你是对的!谢谢!

标签: spring thymeleaf


【解决方案1】:

我只是将th:object="${userForm} 属性添加到我的表单元素中。现在它工作正常!

【讨论】:

    猜你喜欢
    • 2015-03-20
    • 2018-06-09
    • 2016-01-21
    • 2017-03-28
    • 2019-10-21
    • 2015-02-01
    • 2016-02-28
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多