Mic*_*ght 5 thymeleaf spring-boot
我正在使用 Spring Boot 和 thymeleaf 作为 Web 应用程序。
\n\n我想自定义验证错误消息而不是使用默认消息。我发现这样做的方法是创建一个名为 messages.properties 的文件,其中包含约束和消息。我还发现我可以根据我的目标类创建自定义消息,并且我还可以基于此使用国际化方法。
\n\n为了覆盖默认消息,我创建了自己的 messages.properties 文件:
\n\nSize.message=El tam\xc3\xb1o no es correcto\nNotNull.message=No puede ser nulo\nMin.message=No cumple con el minimo\nRun Code Online (Sandbox Code Playgroud)\n\n我在班级中设置了约束:
\n\npublic class Person {\n\n @Size(min=2, max=30)\n private String name;\n\n @NotNull\n @Min(value = 18L)\n private Integer age;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getAge() {\n return age;\n }\n\n public void setAge(Integer age) {\n this.age = age;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这是我的表格:
\n\n<form action="#" th:action="@{/form}" th:object="${person}" method="post">\n\n <table>\n <tr>\n <td>Name:</td>\n <td><input type="text" th:field="*{name}"/></td>\n <td th:if="${#fields.hasErrors(\'name\')}" th:errors="*{name}">Name error</td>\n </tr>\n <tr>\n <td>Age:</td>\n <td><input type="text" th:field="*{age}"/></td>\n <td th:if="${#fields.hasErrors(\'age\')}" th:errors="*{age}">Name error</td>\n </tr>\n <tr>\n <td>\n <button type="submit">Enviar</button>\n </td>\n </tr>\n </table>\n\n</form>\nRun Code Online (Sandbox Code Playgroud)\n\n我将 messages.properties 放在 resources 文件夹中:
\n\n\n\n根据这些链接我做得正确:
\n\nThymeleaf:如何在 JSR-303 注释中使用自定义消息密钥
\n\n如何在 thymeleaf 中包含 message.properties
\n\n但它仍然不显示我编写的自定义错误消息。
\n\n有什么建议吗?\n提前感谢您的帮助。
\n\n带有示例代码的 GitHub:https://MichaelKnight@github.com/MichaelKnight/ValidandoFormularios.git
\n最后我得到了它!
我必须使用对象名称而不是 ClassName,它就像一个魅力。NotNull.person.age=THE AGE CANNOT BE NULL!!!!
我将代码上传到 github,供其他成员进一步参考。
| 归档时间: |
|
| 查看次数: |
9362 次 |
| 最近记录: |