I just started using spring MVC and unable to show proper error message on validation failure.
Controller is :
@RequestMapping(value = "/MobiusDashboardWebsiteContent/csiBatchSubmission", method = RequestMethod.POST)
@LogAction(actionPerformed = "submitCSIBatch")
public String submitCSIBatch(ManualCSIBatch manualCSIBatch, BindingResult result, Model model, MobiusAuthenticationToken authToken) throws Throwable {
ManualCSIBatch mBatch = new ManualCSIBatch();
manualCSIBatch.setBatchUser(getUserName(authToken));
csiBatchValidator.validate(manualCSIBatch, result);
if (result.hasErrors()) {
LOG.error("Validation errors found for the batch " + manualCSIBatch.getBatchName() + " error code is " + manualCSIBatch.getErrorCode());
model.addAttribute("localeList", localeList);
model.addAttribute("evaluateAttributeList", evaluateAttibutes);
model.addAttribute("csiBatchSubmission", manualCSIBatch);
return "csiBatchSubmission";
}
mBatch.setErrorCode(StatusCode.SUCESS.getCode());
model.addAttribute("csiBatchSubmission", mBatch);
return "csiBatchSubmission";
}
Validator is:
@Override
public void validate(Object target, Errors errors) {
ManualCSIBatch manualCSIBatch = (ManualCSIBatch) target;
boolean isDuplicate = getiMobiusService().checkDuplicateCSIBatchName(manualCSIBatch.getBatchName(), manualCSIBatch.getBatchUser());
if (isDuplicate) {
logger.debug("This is a duplicate batch " + manualCSIBatch.getBatchName() + " for this user " + manualCSIBatch.getBatchUser());
errors.rejectValue("batchName", "errors.csi.duplicateBatch", new Object[] { manualCSIBatch.getBatchName() }, null);
}
When validation fails, everything goes fine, form doesn’t submit but error value is not being populated on the UI.
JSP is like this :
<div class="row">
<label for="batch-name"><spring:message code="csi.label.batchname"/></label><form:input path="batchName" onkeyup="checkDuplciateBatch(this.value);" onblur="checkDuplciateBatch(this.value);"/>
<span id="availmsg" style="display:none"></span>
<form:errors path="batchName" cssClass="error"/>
</div>
In all the examples I saw, this is the way. What might be wrong in here?
Thanks,
So here we go.
I came to know that BindingResult is maped to each model attribute.
As per, http://blog.nigelsim.org/2011/09/07/spring-mvc-validation-bindingresult/ adding @ModelAttribute before Model object solved the problem!! Awesome! 🙂