【发布时间】:2014-04-08 21:10:31
【问题描述】:
我正在将 Spring jsp 应用程序迁移到 Thymeleaf,但在显示表单错误时遇到问题。
我正在使用 SpringTemplateEngine 和 ThymeleafViewResolver 并且模板的渲染工作正常。 表单值也填充在表单输入字段中。
目前唯一不起作用的是显示表单错误消息。
我的控制器看起来像:
@RequestMapping(method = RequestMethod.POST)
String save(@Valid CustomerForm form, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute("form", form)
return "app/customers/create"
}
....
我打印了 bindingResult 以验证它是否包含错误:
binding result = org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'customerForm' on field 'name': rejected value []; codes [customerForm.name.NotBlank,name.NotBlank,java.lang.String.NotBlank,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [customerForm.name,name]; arguments []; default message [name]]; default message [may not be empty]
当我尝试显示错误时:
<ul>
<li th:each="e : ${#fields.detailedErrors()}" th:class="${e.global}? globalerr : fielderr">
<span th:text="${e.global}? '*' : ${e.fieldName}">The field name</span> |
<span th:text="${e.message}">The error message</span>
</li>
</ul>
它没有显示任何错误。
我尝试了http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#validation-and-error-messages 上记录的各种替代方法,但没有成功。
我错过了什么吗?
编辑
注意我试图在通过 th:object: 设置的表单中显示错误:
<form id="customer-form" action="#" th:action="@{/app/customers}" th:object="${form}" method="post" class="form-horizontal">
<ul>
<li th:each="e : ${#fields.detailedErrors()}" th:class="${e.global}? globalerr : fielderr">
<span th:text="${e.global}? '*' : ${e.fieldName}">The field name</span> |
<span th:text="${e.message}">The error message</span>
</li>
</ul>
</form>
【问题讨论】:
-
您是否在
form元素中包含了带有错误的ul标记?我用我的代码检查了这一点,当包含在“表单”元素中时它工作正常,否则 - 不是。 -
感谢 Rafal,我正在尝试在使用 th:object 设置的表单中显示错误。我已更新问题以反映这一点。
-
我的代码略有不同,但效果很好。我的代码的不同之处在于,我没有将表单显式填充回模型 (
model.addAttribute("form", form)),因为它是自动添加的。从以前开始,我总是不仅用@Valid标记输入参数,还用@ModelAttribute标记输入参数。也许你可以试一试。