Tuesday, June 9, 2009

User-friendly binding error messages in Spring MVC

In some cases, Spring's binding error messages are not fit to display to the user. How can we get around this? If we override SimpleFormController.onBindAndValidate() in our controller, in the hopes of modifying the BindException parameter accordingly, we'll be hard-pressed to find methods allowing us to do so.

One way to display user-friendly binding error messages is to override SimpleFormController.onBindAndValidate() as follows:

@Override
protected void onBindAndValidate(HttpServletRequest request, Object command,
BindException errors) throws Exception {
if (errors.hasErrors()) {
Map errorsMap = new HashMap();
List errorList = errors.getAllErrors();
for (FieldError error : errorList) {
String msg = "";
try {
msg = this.translate(error.getCode(), error.getArguments());
} catch (Exception e) {}
if (msg.contains("quantity")) {
msg = msg.replace(error.getField(), "quantity");
} else if (msg.contains("unitPrice")) {
msg = msg.replace(error.getField(), "unit price");
}
msg += ".";
errorsMap.put(error.getField(), msg);
}
request.setAttribute("errorsMap", errorsMap);
}
}
This creates a map of user-friendly error messages, keyed by the field names with which the error messages are associated. You can then use it in your JSP, possibly with the tag.

No comments: