0

I'm new to mvc spring and I have some code from the internet like the following:

@RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
    Contact newContact = new Contact();
    model.addObject("contact", newContact);
    model.setViewName("ContactForm");
    return model;
}

@RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(@ModelAttribute Contact contact) {
    contactDAO.saveOrUpdate(contact);
    return new ModelAndView("redirect:/");
}

@RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
    int contactId = Integer.parseInt(request.getParameter("id"));
    contactDAO.delete(contactId);
    return new ModelAndView("redirect:/");
}

My question is, what is the purpose of using and using in any case with @ ModelAttribute, ModelAndView mode and HttpServletRequest request? Thanks you.

Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
Cao Tran
  • 13
  • 4

1 Answers1

0

Please check https://stackoverflow.com/a/33422321/3530898. I my opinion ModelAttribute is used usually with form transport objects (i.e. bean classes whose fields contain the form data), ModelAndView is used when you want to set view name and model object in a single method of a controller. Both ModelAndView and Model uses HttpServletRequest internally, Spring has added wrapper classes over HttpServletRequest to make development easier for developer. But sometime you need HttpServletRequest class for instance, when you want to capture a query parameter in an Ajax call etc

Amit K Bist
  • 6,760
  • 1
  • 11
  • 26