我正在将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注释中使用自定义消息密钥
但是它仍然不显示我编写的自定义错误消息。
有什么建议吗?在此先感谢您的帮助。
带有示例代码的GitHub:https://[email protected]/MichaelKnight/ValidandoFormularios.git
最后我明白了!
我不得不使用对象名称来代替ClassName,它的工作原理就像一个魅力。 NotNull.person.age=THE AGE CANNOT BE NULL!!!!
我将代码上传到github,以供任何其他成员参考。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句