DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • MLOps: Definition, Importance, and Implementation
  • Multi-Stream Joins With SQL
  • DevOps Pipeline and Its Essential Tools
  • The Native Way To Configure Path Aliases in Frontend Projects
  1. DZone
  2. Data Engineering
  3. Databases
  4. Using Spring MVC’s @ModelAttribute Annotation

Using Spring MVC’s @ModelAttribute Annotation

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

Roger Hughes user avatar by
Roger Hughes
·
Aug. 14, 19 · Tutorial
Like (13)
Save
Tweet
Share
320.33K Views

Join the DZone community and get the full member experience.

Join For Free

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!

Annotation Spring Framework Database

Published at DZone with permission of Roger Hughes, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • MLOps: Definition, Importance, and Implementation
  • Multi-Stream Joins With SQL
  • DevOps Pipeline and Its Essential Tools
  • The Native Way To Configure Path Aliases in Frontend Projects

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: