我已经开始学习使用 Spring MVC 的验证注释。 到目前为止,一切都很顺利,但现在我遇到了一个问题,让我停了下来。 当从网页字段返回的字符串被解析为 Long 时,但该字符串包含非数字字符,则会引发异常。虽然这是预期的行为,但事实证明,呈现用户友好的错误消息是一个挑战。
到目前为止我所拥有的:
在webpage.jsp中,Spring错误的显示方式为:
<form:errors path="numberField" cssclass="error"></form:errors>
在网页的 Controller 中,我们有:
@RequestMapping(method = RequestMethod.POST)
public String post(Model model, @Valid @ModelAttribute Item item, BindingResult bindingResult) {
//Stuff
return "redirect:" + ITEM_PAGE;
}
Item 类在成员上有验证注释,并且它们都按预期工作。
从jsp上相应字段旁边的绑定(bind)结果返回的错误消息是:
Failed to convert property value of type java.lang.String to required type java.lang.Long for property quantity; nested exception is java.lang.NumberFormatException: For input string: "n0t"
正如我上面所说,这并不意外,但我想用类似的内容替换该消息
Please input a number
我希望将额外代码保持在最少量,但如果唯一的方法是创建我自己的 validator ,我可能会走这条路。是否有其他方法来处理异常并返回更好的错误消息?
谢谢!
抱歉,这不是可运行的代码,但我无法再发布任何内容。
最佳答案
您需要定义自定义转换错误消息。假设您有 MessageSource
在 Spring 配置中进行设置,将类似的内容添加到包含翻译消息的属性文件中:
typeMismatch.java.lang.Integer = Please enter a number
这将覆盖整数转换失败时默认的用户不友好消息。同样,您可以为其他数据类型定义转换错误消息,例如:
typeMismatch.java.time.LocalDate = Enter a valid date
您还可以为特定字段定义转换错误消息,而不是一般的数据类型。看我的other SO post有关此的更多详细信息。
如果您没有配置 MessageSource
,如果您使用 Java 配置,则可以这样做:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/messages/messages");
return messageSource;
}
关于java - Spring数据绑定(bind)(@modelattribute)优雅地处理解析异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28381335/