1

我在使用 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>

控制器

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

我尝试jobsaveJob方法中传递,但是这样不会显示错误...

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

4

2 回答 2

2

您需要声明与以下内容匹配的模型属性的modelAttribute名称<form>

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

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

于 2013-07-08T09:06:12.120 回答
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";
}
于 2013-07-08T08:43:31.933 回答