英文:
Thymeleaf returning Java Exception message instead of my custom error message. How can I make it return what I want?
问题
我正在实现表单验证,在 Thymeleaf 的错误消息中对 BigInteger 进行验证时遇到问题。这是我的属性注释:
@Digits(integer = 9, fraction = 0, message="必须是正整数")
private BigInteger myInteger;
控制器部分:
@PostMapping("/")
public String whatever(@Valid @ModelAttribute Entity myEntity, BindingResult result) {
if (result.hasErrors()) {
return "index";
}
//TODO
return "index";
}
最后,HTML 代码部分:
<span th:if="${#fields.hasErrors('myEntity.myInteger')}"
th:errors="*{myEntity.myInteger}"></span>
现在,这对于我的其他 BigDecimal 变量效果良好,但是 BigInteger 导致 Thymeleaf 显示 NumberFormatException
而不是我的自定义消息 "必须是正整数。"
,可能是因为我不熟悉的一些错误处理优先级的原因。我已经尝试寻找答案,但大多数答案都指向了基于 messages.properties
的解决方案,而我项目文件夹中没有这个文件。我需要做什么才能确保显示我的自定义消息而不是 NumberFormatException
?
英文:
I am implementing form validation and running into problems with BigInteger validation in thymeleaf's error messages. Here is my property annotation:
@Digits(integer = 9, fraction = 0, message="Must be a positive integer")
private BigInteger myInteger;
The Controller:
@PostMapping("/")
public String whatever(@Valid @ModelAttribute Entity myEntity, BindingResult result) {
if (result.hasErrors()) {
return "index";
}
//TODO
return "index";
}
And finally, the HTML code
<span th:if="${#fields.hasErrors('myEntity.myInteger')}"
th:errors="*{myEntity.myInteger}"></span>
Now, this is working fine for my other BigDecimal variables, but BigInteger causes Thymeleaf to display a NumberFormatException
instead of my custom message "Must be a positive integer."
, presumably because of some priority in error-handling that I am unfamiliar with. I have tried looking for answers but most of them direct me to some messages.properties
based solution, which is not present in my project folder. What do I need to do to ensure my custom message is displayed instead of the NumberFormatException
?
答案1
得分: 1
你可以在 resources
文件夹中创建 messages.properties
,然后添加 typeMismatch.table.myInteger = 必须是正整数
。其中“table”是你的实体名称,使用小写形式。
英文:
You can just create messages.properties
in resources
folder and add typeMismatch.table.myInteger = Must be a positive integer
. Where "table" is your entity name in lower case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论