Spring Boot + Thymeleaf自定义错误消息

迈克尔·奈特

我正在将Spring Boot和thymeleaf用于Web应用程序。

我想自定义验证错误消息,而不是使用默认消息。我发现完成此操作的方法是使用约束和消息创建一个名为messages.properties的文件。我还发现我可以基于要定位的类创建自定义消息,也可以基于此类使用国际化方法。

为了覆盖默认消息,我创建了自己的messages.properties文件:

Size.message=El tamño no es correcto
NotNull.message=No puede ser nulo
Min.message=No cumple con el minimo

我在课堂上设置了约束:

public class Person {

    @Size(min=2, max=30)
    private String name;

    @NotNull
    @Min(value = 18L)
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

这是我的表格:

<form action="#" th:action="@{/form}" th:object="${person}" method="post">

    <table>
        <tr>
            <td>Name:</td>
            <td><input type="text" th:field="*{name}"/></td>
            <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name error</td>
        </tr>
        <tr>
            <td>Age:</td>
            <td><input type="text" th:field="*{age}"/></td>
            <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name error</td>
        </tr>
        <tr>
            <td>
                <button type="submit">Enviar</button>
            </td>
        </tr>
    </table>

</form>

然后将messages.properties放在资源文件夹中:

在此处输入图片说明

根据这些链接,我做得正确:

Thymeleaf:如何在JSR-303注释中使用自定义消息密钥

如何在胸腺中包含message.properties

但是它仍然不显示我编写的自定义错误消息。

有什么建议吗?在此先感谢您的帮助。

带有示例代码的GitHub:https://[email protected]/MichaelKnight/ValidandoFormularios.git

迈克尔·奈特

最后我明白了!

我不得不使用对象名称来代替ClassName,它的工作原理就像一个魅力。 NotNull.person.age=THE AGE CANNOT BE NULL!!!!

我将代码上传到github,以供任何其他成员参考。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Spring Boot和自定义404错误页面

在自定义spring boot登录表单上显示错误登录消息

用于InsufficientAuthenticationException的Spring Boot自定义错误对象

Spring Boot自定义http错误响应?

在错误Spring Boot Rest API期间自定义HTTP响应消息

Spring Boot AccessDecisionVoter自定义未授权消息

自定义Spring错误消息

Spring Boot和Spring Security在AuthenticationEntryPoint中无法通过自定义消息发送错误

Spring Boot API自定义错误响应合同

Spring Boot:配置自定义MethodSecurityExpressionOperations?

自定义主体错误消息-Spring Boot REST

在Spring Boot中无法使用自定义HttpMessageNotReadableException错误消息

如何在Thymeleaf和Spring Boot中使用自定义标签库?

Spring Boot REST API / Spring Security:身份验证失败时返回自定义消息

将自定义Thymeleaf模板解析器添加到Spring Boot

Spring Boot自定义错误页面堆栈跟踪

Spring Boot自定义HttpMessageConverter

有什么方法可以通过spring-boot自定义验证来使用两个自定义错误消息?

Spring Boot-自定义验证消息

Spring Boot如何在验证@PathVariable参数时返回自定义错误消息

Spring Boot显示针对不同异常的自定义错误消息

spring-boot中的自定义404错误页面

Spring boot 禁用自定义 HealthIndicator

spring boot中的自定义错误页面

捕获 404 错误 spring boot 以返回自定义 html

Spring boot 配置自定义sql

Spring boot + Thymeleaf 在自定义片段中显示数据库记录

Spring Boot Actuator - 自定义端点

Thymeleaf 在没有 spring boot 的情况下调用自定义 java 类