我使用Spring-boot和Thymeleaf模板引擎,我尝试使用th:classappend
属性添加可选" has-error"等级< div>使用#fields.hasErrors('*')
表达式
<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>
但我有这个错误
无法使用表达式&#34; *&#34;来绑定表单错误。请检查一下 表达式正在适当的上下文中执行(例如 使用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";
}
我做错了什么?
答案 0 :(得分:0)
我只是将th:object="${userForm}
属性添加到我的表单元素中。现在它工作正常!