在Spring MVC中验证失败后无法显示正确的错误消息

时间:2012-12-25 08:41:42

标签: validation model-view-controller spring-mvc uiviewcontroller

我刚开始使用spring MVC,无法在验证失败时显示正确的错误消息。

控制器是:

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

验证者是:

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

当验证失败时,一切正常,表单没有提交但是UI上没有填充错误值。

JSP就像这样:

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

在我看到的所有例子中,这就是方法。这里可能有什么问题?

谢谢,

1 个答案:

答案 0 :(得分:1)

所以我们走了。

我开始知道BindingResult被映射到每个模型属性。

按照http://blog.nigelsim.org/2011/09/07/spring-mvc-validation-bindingresult/在Model对象解决问题之前添加@ModelAttribute !!真棒! :)