Thymeleaf 不显示 Spring 表单错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22948257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:39:41  来源:igfitidea点击:

Thymeleaf not displaying Spring form error messages

springthymeleaf

提问by Marcel Overdijk

I'm migrating a Spring jsp application to Thymeleaf but having problems displaying form errors.

我正在将 Spring jsp 应用程序迁移到 Thymeleaf,但在显示表单错误时遇到问题。

I'm using the SpringTemplateEngine and ThymeleafViewResolver and rendering of templates works. Also form values are populated in form input fields.

我正在使用 SpringTemplateEngine 和 ThymeleafViewResolver 并且模板的渲染工作。表单值也填充在表单输入字段中。

The only thing so far not working is displaying form error messages.

到目前为止唯一不起作用的是显示表单错误消息。

My controller looks like:

我的控制器看起来像:

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

I printed the bindingResult to verify it contains an error:

我打印了 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]

When I try to display error using:

当我尝试使用以下方法显示错误时:

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

it does not display any error.

它不显示任何错误。

I tried various alternatives as documented on http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#validation-and-error-messagesbut without success.

我尝试了http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#validation-and-error-messages 上记录的各种替代方案,但没有成功。

Am I missing something?

我错过了什么吗?

EDIT

编辑

Note I'm trying to display the error within a form set via th:object:

注意我试图在通过 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>

回答by Gary Hellman

I think you may be having the same issue as I did - please see :

我想你可能和我有同样的问题 - 请参阅:

There it is answered by Daniel Fernandez. Basically your form object th:object="${form}"is named "form"butyour controller is looking for "customerForm"(class name) not"form"(the variable name)

在那里由 回答Daniel Fernandez。基本上您的表单对象th:object="${form}"已命名,"form"您的控制器正在寻找"customerForm"(类名)而不是"form"(变量名)

can be renamed with @ModelAttribute("data")

可以重命名 @ModelAttribute("data")

copied from that link use:

从该链接复制使用:

public String post(@Valid FormData formData, BindingResult result, Model model){
    // th:object="${formData}"
}

or

或者

public String post(@Valid @ModelAttribute("data") FormData data, BindingResult result, Model model){
    // th:object="${data}"
} 

回答by Blejzer

This is how I do it in my forms:

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

For displaying all errors I put this at the beginning of my form:

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

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

and for individual error I add this after the field (of course, changing field in hasErrors to correspond to the field tested):

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

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

Let me know if this works for you?

让我知道这对你有用吗?

回答by Ayman Al-Absi

Adding to @Blejzer answer: naming of error message inside messages.properties file must follow below naming convention, so message string will be returned instead of message key:

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

(Constraint Name).(Object Name).(Property Name)

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

note: Object Name not Class Name

注意:对象名不是类名

For example, if you have below User class:

例如,如果您有以下 User 类:

class User{
    @NotBlank
    String username;

    @Length(min=6)
    String password;
}

suppose in controller, we named object under validation "user", see @ModelAttribute("user"):

假设在控制器中,我们将验证下的对象命名为“ 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";
}

in above controller snippet, the object name is "user" not "User"

在上面的控制器片段中,对象名称是“用户”而不是“用户”

Now, to show custom messages, you have to name the message as below:

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

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