Search code examples
spring-mvcmodelattribute

Spring MVC @ModelAttribute method


Question about Spring MVC @ModelAttribute methods, Setting model attributes in a controller @RequestMapping method verses setting attribute individually with @ModelAttribute methods, which one is considered better and is more used?

From design point of view which approach is considered better from the following:

Approach 1

@ModelAttribute("message")
public String addMessage(@PathVariable("userName") String userName, ModelMap model) {

  LOGGER.info("addMessage - " + userName);
  return "Spring 3 MVC Hello World - "  + userName;
}

@RequestMapping(value="/welcome/{userName}", method = RequestMethod.GET)
public String printWelcome(@PathVariable("userName") String userName, ModelMap model) {

  LOGGER.info("printWelcome - " + userName);
  return "hello";
}   

Approach 2

@RequestMapping(value="/welcome/{userName}", method = RequestMethod.GET)
public String printWelcome(@PathVariable("userName") String userName, ModelMap model) {

  LOGGER.info("printWelcome - " + userName);

  model.addAttribute("message", "Spring 3 MVC Hello World - "  + userName);

  return "hello";
}   

Solution

  • One is not better then the other. They both serve another purpose.

    • Method: If you need the model for a particular controller to be always populated with certain attributes the method level @ModelAttribute makes more sense.
    • Parameter: Use it on a parameter when you want to bind data from the request and add it to the model implicitly.

    To answer your question on the better approach

    I would say approach 2 is better since the data is specific to that handler.