2015-02-07 45 views
1

我已经开始学习使用Spring MVC的验证注释。 到目前为止,一切都进展顺利,但现在我遇到了一个问题,使我停下脚步。 从网页字段返回的字符串被解析为Long时,会引发异常,但该字符串包含非数字字符。虽然预期的行为,提出用户友好的错误信息被证明是一个挑战。Spring数据绑定(@modelattribute)优雅地处理解析异常

我到目前为止有:

在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类具有对成员的验证注释,它们都按预期工作。

从bindingResult在JSP旁边的相应字段错误消息回报是:

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 

我想保持它最少量的额外的代码,但如果唯一的办法就是创建自己的验证,我可能会走这路线。是否有其他方法来处理异常并返回更好的错误消息?

谢谢!

对不起,这不是可运行的代码,但我不能再发布。

回答

3

您需要定义自定义转换错误消息。假设你有你的Spring配置的MessageSource设置,添加像这样到包含翻译信息的属性文件:

typeMismatch.java.lang.Integer = Please enter a number 

这将覆盖失败整数转换默认用户不友好的消息。同样,你可以定义转换错误消息其他数据类型,如:

typeMismatch.java.time.LocalDate = Enter a valid date 

您还可以定义转换错误消息的具体领域,而不是一般的数据类型。有关详细信息,请参阅我的other SO post

@Bean 
public MessageSource messageSource() { 
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
    messageSource.setBasename("/WEB-INF/messages/messages"); 
    return messageSource; 
} 
+0

干杯:


如果你没有MessageSource配置,比如,你可以这样,如果你使用的Java配置做到这一点。我会尽快尝试,我会让你知道的! – 2015-02-07 17:00:51