0

I'm using Spring 3.1.0.RELEASE. For some reason, in my controller, when I POST my form and return the original screen when an error occurs, model attributes are not getting populated like they do when I invoke the page through a GET method. In my controller I have

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

What am I doing wrong and how can I correct it?

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

1

When you return to the upload/index view from the POST, it is not re-populating the Model, since your code to populate the model is done on the GET.

One potential option is to use the @ModelAttribute annotation in your Controller class

You would have, for example, a method that looks like this for the StandardsUploadItem:

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

You could then remove the line below from your GET method:

model.addAttribute(new StandardsUploadItem());

Since a method annotated with @ModelAttribute and returning an object will automatically be put in the ModelMap, regardless of which Controller RequestMapping method is activated.

Your method signature for the POST method would contain something like this:

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

You would need to do something similar for the other attributes in your model (gradeList, and subjectList), but since you do not seem to need them on the POST, you could do something like add a Model parameter to your POST method signature, and re-populate that Model before you return the ModelAndView in the error case.

Community
  • 1
  • 1
Matt
  • 3,455
  • 1
  • 17
  • 6