【问题标题】:Why isn't my Spring Model getting populated with the proper attributes?为什么我的 Spring 模型没有填充正确的属性?
【发布时间】:2012-09-25 21:55:25
【问题描述】:

我正在使用 Spring 3.1.0.RELEASE。出于某种原因,在我的控制器中,当我发布表单并在发生错误时返回原始屏幕时,模型属性不会像我通过 GET 方法调用页面时那样填充。在我的控制器中,我有

@Controller
public class StandardsUploadController {

    …
    @RequestMapping(value = "/upload")
    public String getUploadForm(Model model) {
        model.addAttribute(new StandardsUploadItem());
        model.addAttribute("gradeList", gradeList);
        model.addAttribute("subjectList", subjectList);
        return "upload/index";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView processFile(final StandardsUploadItem uploadItem,
        final BindingResult result, 
        final HttpServletRequest request,
        final HttpServletResponse response) throws InvalidFormatException, CreateException, NamingException {

        stdsUploadValidator.validate(uploadItem, result);
        if (!result.hasErrors()) {
            try {
                …       
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
                e.printStackTrace();
            }
        }   // if

        return new ModelAndView("upload/index");
    }

我做错了什么,我该如何纠正?

【问题讨论】:

    标签: spring model attributes controller


    【解决方案1】:

    当您从 POST 返回到上传/索引视图时,它不会重新填充模型,因为填充模型的代码是在 GET 上完成的。

    一种可能的选择是在 Controller 类中使用 @ModelAttribute 注释

    例如,StandardsUploadItem 的方法如下所示:

    @ModelAttribute("uploadItem")
    public StandardsUploadItem getStandardsUploadItem(){
        return new StandardsUploadItem();
    }
    

    然后您可以从 GET 方法中删除以下行:

    model.addAttribute(new StandardsUploadItem());
    

    由于使用@ModelAttribute注解并返回对象的方法将自动放入ModelMap中,无论激活哪个Controller RequestMapping方法。

    您的 POST 方法的方法签名将包含如下内容:

    ..., @ModelAttribute("uploadItem") StandardsUploadItem uploadItem, ...
    

    您需要对模型中的其他属性(gradeList 和 subjectList)执行类似的操作,但由于您在 POST 上似乎不需要它们,您可以执行一些操作,例如将模型参数添加到您的 POST 方法签名,并在错误情况下返回 ModelAndView 之前重新填充该模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多