【问题标题】:Spring databinding (@modelattribute) gracefully handle parse exceptionsSpring 数据绑定(@modelattribute)优雅地处理解析异常
【发布时间】:2015-02-07 11:00:48
【问题描述】:

我已经开始学习使用 Spring MVC 的验证注解。 到目前为止,一切进展顺利,但现在我遇到了一个问题,这让我停了下来。 从网页字段返回的字符串被解析为 Long 时抛出异常,但该字符串包含非数字字符。虽然是预期的行为,但提供用户友好的错误消息被证明是一个挑战。

到目前为止我所拥有的:

在webpage.jsp中,Spring错误被显示为:

<form:errors path="numberField" cssclass="error"></form:errors>

在网页的控制器中,我们有:

@RequestMapping(method = RequestMethod.POST)
public String post(Model model, @Valid @ModelAttribute Item item, BindingResult bindingResult) {

//Stuff

return "redirect:" + ITEM_PAGE;
}

Item 类在成员上具有验证注释,它们都按预期工作。

jsp上相应字段旁边的bindingResult返回的错误信息是:

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

我想尽量减少额外的代码,但如果唯一的方法是创建自己的验证器,我可能会走这条路。还有其他方法可以处理异常并返回更好的错误消息吗?

谢谢!

抱歉,这不是可运行的代码,但我不能再发布了。

【问题讨论】:

    标签: java spring spring-mvc exception annotations


    【解决方案1】:

    您需要定义自定义转换错误消息。假设您在 Spring 配置中有一个 MessageSource 设置,请在包含翻译消息的属性文件中添加如下内容:

    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;
    }
    

    【讨论】:

    • 干杯。我一有机会就试试这个,我会告诉你的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 2023-03-21
    • 1970-01-01
    • 2017-02-18
    • 2016-07-30
    • 2017-03-04
    • 2014-03-29
    相关资源
    最近更新 更多