Spring databinding (@modelattribute) gracefully ha

2019-07-30 04:49发布

问题:

I've begun learning to use Spring MVC's validation annotations. So far, everything has been going well, but now I've come across an issue which has halted me in my tracks. An exception is being thrown when the string returned from a webpage field is being parsed into a Long, but the string contains non numeric characters. Whilst expected behaviour, presenting a user friendly error message is proving to be a challenge.

What I have so far:

in webpage.jsp, the Spring error is being displayed by:

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

In the controller for the webpage, we have:

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

//Stuff

return "redirect:" + ITEM_PAGE;
}

Item class has validation annotations on the members and they all work as expected.

The error message return from the bindingResult on the jsp next to the appropriate field is:

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"

As I've said above, this is not unexpected, but I would like to replace that message with something like

Please input a number

I'd like to keep it to minimal amounts of extra code, but if the only way is to create my own validator, I might go down that route. Are there any other ways to handle the exception and return a nicer error message?

Thanks!

Sorry that this is not runnable code, but I cant post any more.

回答1:

You need to define custom conversion error message. Assuming that you have a MessageSource set-up in your Spring configuration, add something like this to the properties file containing your translation messages:

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

That will override the default user unfriendly message for failed integer conversions. Similarly you can define conversion error messages for other data types, like:

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

You can also define conversion error messages for specific fields, rather than datatypes in general. See my other SO post for more details about this.


If you don't have MessageSource configured, you can do it for example like this if you use Java configuration:

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