我正在将一个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>
发布于 2014-04-12 03:35:30
我想你可能和我有同样的问题--请看:
在那里,它由Daniel Fernandez
回答。基本上,您的表单对象th:object="${form}"
被命名为"form"
,但是您的控制器查找的是"customerForm"
(类名),而不是 "form"
(变量名)
可以使用@ModelAttribute("data")
重命名
使用以下链接从该链接复制:
public String post(@Valid FormData formData, BindingResult result, Model model){
// th:object="${formData}"
}
或
public String post(@Valid @ModelAttribute("data") FormData data, BindingResult result, Model model){
// th:object="${data}"
}
https://stackoverflow.com/questions/22948257
复制相似问题