【问题标题】:Thymeleaf not displaying Spring form error messagesThymeleaf 不显示 Spring 表单错误消息
【发布时间】: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 标记输入参数。也许你可以试一试。

标签: spring thymeleaf


【解决方案1】:

我认为您可能遇到与我相同的问题 - 请参阅:

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

【讨论】:

  • 这对我也有用。谢谢。充分尊重“Spring In Action,第 5 版”一书,作者在代码示例中没有提到这一点,我努力使其工作。
【解决方案2】:

这就是我在表单中的做法:

为了显示所有错误,我将其放在表单的开头:

<div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
    <p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>    
</div>

对于个别错误,我在字段之后添加这个(当然,更改 hasErrors 中的字段以对应于测试的字段):

<p th:if="${#fields.hasErrors('vehicle.licensePlate')}" class="label label-danger" th:errors="*{vehicle.licensePlate}">Incorrect LP</p>

让我知道这是否适合你?

【讨论】:

  • 这正是我想要的。
  • 对我来说这给出了:无法使用表达式“*”绑定表单错误。
【解决方案3】:

添加到@Blejzer 答案: messages.properties 文件中错误消息的命名必须遵循以下命名约定,因此将返回消息字符串而不是消息键:

(约束名称)。(对象名称)。(属性名称)

注意:对象名不是类名

例如,如果您有以下用户类:

class User{
    @NotBlank
    String username;

    @Length(min=6)
    String password;
}

假设在控制器中,我们将验证对象命名为“user”,参见@ModelAttribute("user"):

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, Model model) {

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

    //do some processing

    return "redirect:/index";
}

在上面的控制器 sn-p 中,对象名称是“user”而不是“User”

现在,要显示自定义消息,您必须将消息命名如下:

NotBlank.user.username=User Name is blank
Length.user.password=Password length must be at least 6 letters

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2017-04-26
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多