java - Spring数据绑定(bind)(@modelattribute)优雅地处理解析异常

标签 java spring spring-mvc exception annotations

我已经开始学习使用 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/

相关文章:

java - Spring Security 注销和最大 session 数

java - Spring:从哪里获取ApplicationContext?

jakarta-ee - 使用 Spring MVC 时如何在 WEB-INF 之外访问/公开

Java ConcurrentSkipListMap的computeIfAbsent方法 "applied once atomically"

java - 动态初始化对象

java - 使用 Jena ARQ 通过基本身份验证访问远程存储库 - 抢占式

java - 如何在不使用 ComponentScan 的情况下启动 Spring Boot Web 应用程序

java - 以给定的精度快速将double转成string

java - JDBC 最大连接数

java - 来自 Autowiring 对象的 spring 变量注入(inject)