Spring MVC表单验证:缺少模型属性对象

时间:2013-07-08 08:38:34

标签: java spring validation spring-mvc

我在使用Spring MVC处理表单提交时遇到了一个奇怪的问题。

我正在使用Spring 3.1.1并且我正在实现一个简单的表单来将实体插入/编辑到我的数据库中。 我的代码如下:

JSP

<sf:form action="save" method="post" modelAttribute="job">

    <sf:hidden path="id" />
    <span class="wrap">Label:</span> <sf:input path="label" />
    <sf:errors path="label"></sf:errors>

    <span class="wrap">Description:</span> <sf:textarea path="description" />
    <input type="submit" value="save" />
</sf:form>

CONTROLLER

@RequestMapping(value = "/edit")
public String editJob(Integer jobId, Model model) {
    ExportJob job = new ExportJob();
    if (jobId != null && jobId > 0) {
        job = schedulingService.getScheduledJob(jobId);
    }
    model.addAttribute("job", job);
    return VIEW_EDIT_FORM;
}

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveJob(@ModelAttribute ExportJob job, BindingResult result) {

    ExportJobValidator ejValidator = new ExportJobValidator();
    ejValidator.validate(job, result);

    if (result.hasErrors()) {
        return VIEW_EDIT_FORM;
    }
    schedulingService.saveAndSchedule(job);
    return "redirect:/schedule";
}

当模型属性验证失败时,我希望被重定向到表单并显示错误。相反,我得到了这个错误:

  

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'job' available as request attribute

我尝试在job方法中传递saveJob,但这样就没有显示错误......

我不是Spring MVC的专家,所以你能帮我理解我做错了吗?

2 个答案:

答案 0 :(得分:2)

您需要在modelAttribute中声明与<form>匹配的模型属性的名称:

... @ModelAttribute("job") ExportJob job, ...

默认情况下,属性名称将从属性的类名称(exportJob)推断出来,并且在您的情况下不会与modelAttribute匹配。

答案 1 :(得分:0)

以下代码应显示数据绑定期间发生的错误。

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveJob(@ModelAttribute ExportJob job, BindingResult result, 
    ModelMap model) {

    //Debug errors, assumes logger is in place
    if (result.hasErrors()) {
       List<String> fieldErrors = new ArrayList<String>();
       for (FieldError f : result.getFieldErrors()) {
           fieldErrors.add(f.getField() + "=" + f.getRejectedValue().toString());
           log.debug("BindingFailure: {} = {}", new Object[] { f.getField(),
                 f.getRejectedValue() });
    }

    ExportJobValidator ejValidator = new ExportJobValidator();
    ejValidator.validate(job, result);

    if (result.hasErrors()) {
        return VIEW_EDIT_FORM;
    }
    schedulingService.saveAndSchedule(job);
    return "redirect:/schedule";
}