【发布时间】:2016-03-31 00:17:55
【问题描述】:
我正在将 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 : How to use Custom Message Key in JSR-303 Annotation
How to include message.properties with thymeleaf
但它仍然没有显示我写的自定义错误消息。
有什么建议吗? 提前感谢您的帮助。
带有示例代码的 GitHub:https://MichaelKnight@github.com/MichaelKnight/ValidandoFormularios.git
【问题讨论】:
-
你能做一个干净的构建和检查吗?有时,在清理和构建应用程序之前,对 Spring Boot 应用程序所做的更改可能不会反映。
-
@harshavmb 我刚刚做到了。没什么新鲜的:(
标签: spring-boot thymeleaf