使用BindingResult属性的Spring验证永远不会命中目标控制器方法

时间:2013-04-10 13:55:35

标签: java spring-mvc validation spring-validator

我有一个表单,我提交上传文件:

<form id="uploadForm" action="#" method="POST" enctype="multipart/form-data">
    <div class="instruction popup_inst">
        <span class="popup_logo">[@spring.message "pandaLogo"/]</span>

        <div class="float_right">
            <input type="button" id="cancelBtn" class="btn" onclick="closePopupFunctionality();" value="[@spring.message "cancelButton"/]" />

            <input class="btn" type="submit" id="submit" onclick="validateFileInput();" value="[@spring.message "uploadButton"/]" />
        </div>

    </div>
    <span class="popup_title">[@spring.message "uploadFile"/]</span>
    <div class="popup_container">
        [@spring.bind "assayAssessmentsRequestBean"/]
        [@spring.formInput path="assayAssessmentsRequestBean.designabilityFile.file" fieldType="file" attributes="title='path' class='upload' accept='.txt,.csv,.zip'" /]
        [@spring.formHiddenInput path="assayAssessmentsRequestBean.dateOfAssessment" attributes="" /]
        [@spring.formHiddenInput path="assayAssessmentsRequestBean.id" attributes="" /]
        [@spring.showErrors " " "error" /]
    </div>
    <input id="uploadfile" type="hidden" value="${uploadfile}"/>
</form>

此表单在控制器中命中以下方法:

@RequestMapping(value = "/uploadFile",method= RequestMethod.POST)
    public ModelAndView uploadFile(@ModelAttribute(value = "assayAssessmentsRequestBean")AssayAssessmentsRequestBean assayAssessmentsRequestBean,HttpSession session,BindingResult result) throws PanDaApplicationException {
//mycode
}

发生的事情是该方法从未调用过,当我删除BindingResult属性时,调用该方法。

我尝试了另一种方法,它具有BeanPropertyBindingResult属性并传递目标对象以进行验证,它可以工作,但永远不会返回错误。

@RequestMapping(value = "/uploadFile",method= RequestMethod.POST)
    public ModelAndView uploadFile(@ModelAttribute(value = "assayAssessmentsRequestBean")AssayAssessmentsRequestBean assayAssessmentsRequestBean,HttpSession session/*,BindingResult result*/) throws PanDaApplicationException {
        logger.info(assayAssessmentsRequestBean.getDesignabilityFile().getFile());
        BindingResult result=new BeanPropertyBindingResult(assayAssessmentsRequestBean.getDesignabilityFile(),"designabilityFile");

1 个答案:

答案 0 :(得分:3)

你应该在你想要验证的对象之前有@Valid注释,并且BindingResult必须紧跟在经过验证的对象之后

所以这应该做的工作

 public ModelAndView  uploadFile(@Valid @ModelAttribute(
    value = "assayAssessmentsRequestBean")AssayAssessmentsRequestBean   assayAssessmentsRequestBean,BindingResult result,
HttpSession session) {

 }

然后你应该定义自己的Validator并将其设置为binder。验证器将自动调用。 但我不确定你是否可以用这种方式对multipart进行验证。