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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Frequently Used Annotations in Spring Boot Applications
  • Java Enterprise Annotations Part 1
  • Minimizing Latency in Kafka Streaming Applications That Use External API or Database Calls
  • Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable

Trending

  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  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.

By 
Roger Hughes user avatar
Roger Hughes
·
Aug. 14, 19 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
323.0K 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.

Related

  • Frequently Used Annotations in Spring Boot Applications
  • Java Enterprise Annotations Part 1
  • Minimizing Latency in Kafka Streaming Applications That Use External API or Database Calls
  • Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!