{{announcement.body}}
{{announcement.title}}

Using Spring MVC’s @ModelAttribute Annotation

DZone 's Guide to

Using Spring MVC’s @ModelAttribute Annotation

Learn more about using Spring MVC's @ModelAttribute annotation.

· Java Zone ·
Free Resource

The @ModelAttribute annotation is used as part of a Spring MVC web app and can be used in two scenarios.

  • Firstly, it can be used to inject data objects in the model before a JSP loads. This makes it particularly useful by ensuring that a JSP has all the data it needs to display itself. The injection is achieved by binding a method return value to the model.
  • Secondly, it can be used to read data from an existing model, assigning it to handler method parameters.

To demonstrate the  @ModelAttributes, I'm using the simplest of scenarios: adding a user account to a hypothetical system and then, once the user account has been created, displaying the new user’s details on a welcome screen.

To get the ball rolling, I’ll need a simple User bean with some familiar fields: first name, last name, nickname, email address — the usual suspects.

public class User {

  private String firstName;

  private String lastName;

  private String nickName;

  private String emailAddress;

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getNickName() {
    return nickName;
  }

  public void setNickName(String nickName) {
    this.nickName = nickName;
  }

  public String getEmailAddress() {
    return emailAddress;
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }
}


I’ll also need a Spring MVC controller to handle creating users. This will contain a couple of important methods that use the @ModelAttribute annotation, demonstrating the functionality outlined above.

The method below demonstrates how to bind a method return value to a model.

  /**
   * This creates a new address object for the empty form and stuffs it into
   * the model
   */
  @ModelAttribute("User")
  public User populateUser() {
    User user = new User();
    user.setFirstName("your first name");
    user.setLastName("your last name");
    return user;
  }


This method is called before every @RequestMapping-annotated handler method to add an initial object to the model, which is then pushed through to the JSP. Notice the word every in the above sentence. The @ModelAttribute-annotated methods (and you can have more than one per controller) get called irrespective of whether or not the handler method or JSP uses the data. In this example, the second request handler method call doesn’t need the new user in the model, and so, the call is superfluous. Bear in mind that this could possibly degrade application performance by making unnecessary database calls, etc. It’s, therefore, advisable to use this technique only when each handler call in your Controller class needs the same common information adding to the model for every page request. In this example, it would be more efficient to write:

  /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String createForm() {

    populateUser();
    return FORM_VIEW;
  }


The method below demonstrates how to annotate a request method argument so that data is extracted from the model and bound to the argument.

  /**
   * This is the handler method. Stick the user bean into a new attribute for
   * display on the next page
   *
   * @param user
   *            The user bean taken straight from the model
   * @param model
   *            An out param. Takes the user and adds it to the model FOR the
   *            NEXT page under a different name.
   *
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addAddress(@ModelAttribute("user") User user,
      BindingResult result, Model model) {

    model.addAttribute("newUser", user);
    return WELCOME_VIEW;
  }


In this example, an ‘add user’ button on a form has been pressed calling the addUser() method. The addUser() method needs a User object from the incoming model so that the new user’s details can be added to the database. The @ModelAttribute("user") annotation applied takes any matching object from the model with the “user” annotation and plugs it into the User method argument

Just for the record, this is the full controller code.

@Controller
public class AddUserController {

  private static final String FORM_VIEW = "adduser.page";

  private static final String WELCOME_VIEW = "newuser.page";

  private static final String PATH = "/adduser";

  /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String createForm() {

    return FORM_VIEW;
  }

  /**
   * This creates a new address object for the empty form and stuffs it into
   * the model
   */
  @ModelAttribute("User")
  public User populateUser() {
    User user = new User();
    user.setFirstName("your first name");
    user.setLastName("your last name");
    return user;
  }

  /**
   * This is the handler method. Stick the user bean into a new attribute for
   * display on the next page
   *
   * @param user
   *            The user bean taken straight from the model
   * @param model
   *            An out param. Takes the user and adds it to the model FOR the
   *            NEXT page under a different name.
   *
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addAddress(@ModelAttribute("user") User user,
      BindingResult result, Model model) {

    model.addAttribute("newUser", user);
    return WELCOME_VIEW;
  }
}

 

Happy coding!

Topics:
java ,spring ,spring mvc ,modelattribute ,controller

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}