Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring MVC @ModelAttribute Annotation with Example
Next article icon

Spring MVC @ModelAttribute Annotation with Example

Last Updated : 09 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. For example, if we have a form with a form backing object that is called "Student" then we can have Spring MVC supply this object to a Controller method by using the @ModelAttribute annotation:

@RequestMapping("/home")
public String showHomePage(@ModelAttribute("studentInfo") StudentInfoDTO studentInfoDTO) {

return "something";

}

So, let's understand the whole concept of @ModelAttribute Annotation with an interesting example project. Before that, we suggest you please refer to these articles so that it's going to be very easy for you to understand the concept of @ModelAttribute Annotation through an example project. 

  • Data Binding in Spring MVC with Example
  • Two-Way Data Binding in Spring MVC with Example 

Example Project

We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS on your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? Go to your STS IDE then create a new maven project, File > New > Maven Project, and choose the following archetype as shown in the below image as follows:  

Selection of archetype

Add the following maven dependencies and plugin to your pom.xml file. 

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- plugin -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>

Below is the complete code for the pom.xml file after adding these dependencies.

File: pom.xml 

XML
<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">     <modelVersion>4.0.0</modelVersion>     <groupId>com.geeksforgeeks</groupId>     <artifactId>simple-calculator</artifactId>     <packaging>war</packaging>     <version>0.0.1-SNAPSHOT</version>     <name>simple-calculator Maven Webapp</name>     <url>http://maven.apache.org</url>        <dependencies>         <dependency>             <groupId>junit</groupId>             <artifactId>junit</artifactId>             <version>3.8.1</version>             <scope>test</scope>         </dependency>                <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-webmvc</artifactId>             <version>5.3.18</version>         </dependency>                <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->         <dependency>             <groupId>javax.servlet</groupId>             <artifactId>javax.servlet-api</artifactId>             <version>4.0.1</version>             <scope>provided</scope>         </dependency>     </dependencies>        <build>         <finalName>simple-calculator</finalName>         <plugins>             <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-war-plugin</artifactId>                 <version>2.6</version>                 <configuration>                     <failOnMissingWebXml>false</failOnMissingWebXml>                 </configuration>             </plugin>         </plugins>     </build> </project> 

Configuring Dispatcher Servlet

Before moving into the coding part let's have a look at the file structure in the below image. 

Project Structure

So at first create an src/main/java folder and inside this folder create a class named CalculatorAppIntilizer and put it inside the com.geeksforgeeks.calculator.config package and extends the AbstractAnnotationConfigDispatcherServletInitializer class. Refer to the below image.

Class Creation

And whenever you are extending this class, it has some pre abstract methods that we need to provide the implementation. Now inside this class, we have to just write two lines of code to Configure the Dispatcher Servlet. Before that, we have to create another class for the Spring configuration file. So, go to the src/main/java folder and inside this folder create a class named CalculatorAppConfig and put it inside the com.geeksforgeeks.calculator.config package. Below is the code for the CalculatorAppConfig.java file.

File: CalculatorAppConfig.java

Java
package com.geeksforgeeks.calculator.config;  import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;  @Configuration @ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers") public class CalculatorAppConfig {  } 

And below is the complete code for the CalculatorAppIntilizer.java file. Comments are added inside the code to understand the code in more detail.

File: CalculatorAppIntilizer.java

Java
package com.geeksforgeeks.calculator.config;  import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  public class CalculatorAppIntilizer extends AbstractAnnotationConfigDispatcherServletInitializer {      @Override     protected Class<?>[] getRootConfigClasses() {         // TODO Auto-generated method stub         return null;     }      // Registering the Spring config file     @Override     protected Class<?>[] getServletConfigClasses() {         Class aClass[] = { CalculatorAppConfig.class };         return aClass;     }      // Add mapping url     @Override     protected String[] getServletMappings() {         String arr[] = { "/geeksforgeeks.org/*" };         return arr;     }  } 

Setup ViewResolver

Spring MVC is a Web MVC Framework for building web applications. In generic all MVC frameworks provide a way of working with views. Spring does that via the ViewResolvers, which enables you to render models in the browser without tying the implementation to specific view technology. Read more here: ViewResolver in Spring MVC. So for setting up ViewResolver go to the CalculatorAppConfig.java file and write down the code as follows

@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}

And below is the updated code for the CalculatorAppConfig.java file after writing the code for setting up the ViewResolver. 

File: Updated CalculatorAppConfig.java

Java
package com.geeksforgeeks.calculator.config;  import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver;  @EnableWebMvc @Configuration @ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers") public class CalculatorAppConfig {      // setup ViewResolver     @Bean     public InternalResourceViewResolver viewResolver() {         InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();         viewResolver.setPrefix("/WEB-INF/view/");         viewResolver.setSuffix(".jsp");         return viewResolver;     }  } 

Create DTO

Go to the src/main/java folder and inside this folder create a class named NameInfoDTO and put it inside the com.geeksforgeeks.calculator.dto package. Below is the code for the NameInfoDTO.java file. Comments are added inside the code to understand the code in more detail.

File: NameInfoDTO.java

Java
package com.geeksforgeeks.calculator.dto;  public class NameInfoDTO {      // Provided some static values     // inside the variable     // And we are going to read these values     private String firstName = "Anshul";     private String lastName = "Aggarwal";      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;     }      @Override     public String toString() {         return "NameInfoDTO [firstName=" + firstName + ", lastName=" + lastName + "]";     }  } 

Create Controller 

Go to the src/main/java folder and inside this folder create a class named AppController and put it inside the com.geeksforgeeks.calculator.controllers package. Below is the complete code for the AppController.java file.

File: AppController.java file

Java
package com.geeksforgeeks.calculator.controllers;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping;  import com.geeksforgeeks.calculator.dto.NameInfoDTO;  @Controller public class AppController {      @RequestMapping("/home")     public String showHomePage(Model model) {                  // Read the existing property by         // fetching it from the DTO         NameInfoDTO nameInfoDTO = new NameInfoDTO();         model.addAttribute("nameInfo", nameInfoDTO);                  return "welcome-page";     }      @RequestMapping("/process-homepage")     public String showResultPage(NameInfoDTO nameInfoDTO, Model model) {          // writing the value to the properties         // by fetching from the URL         model.addAttribute("nameInfo", nameInfoDTO);          return "result-page";     }   } 

Create View

Now we have to create a view named "welcome-page" inside the WEB-INF/view folder with the .jsp extension. So, go to the src > main > webapp > WEB-INF and create a folder view and inside that folder create a jsp file named welcome-page. So below is the code for the welcome-page.jsp file. 

File: welcome-page.jsp

HTML
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  <html> <head> </head> <body>      <hr />      <form:form action="process-homepage" method="get" modelAttribute="nameInfo">          <div align="center">              <p>                 <label for="name1">Enter First Name : </label>                 <form:input id="name1" path="firstName" />             </p>               <p>                 <label for="name2">Enter Last Name : </label>                  <form:input id="name2" path="lastName" />             </p>               <input type="submit" value="Bind Data" />          </div>      </form:form> </body> </html> 

Now we have to create another view named "result-page" to display the captured values. So below is the code for the result-page.jsp file. 

File: result-page.jsp

HTML
<html> <head> </head> <body>     <hr />      <p>First Name is: ${nameInfo.firstName}</p>       <p>Last Name is: ${nameInfo.lastName}</p>  </body> </html> 

So, now we have done with the coding part. And if you run your application it will work fine but now let's come to the AppController.java file again to understand the concept of @ModelAttribute Annotation. 

Understanding @ModelAttribute Annotation

So, in the AppController.java file, we have written so much code and we can do the same thing using the @ModelAttribute Annotation also. So let's have a look at the code. 

@RequestMapping("/home")
public String showHomePage(Model model) {

// Read the existing property by
// fetching it from the DTO
NameInfoDTO nameInfoDTO = new NameInfoDTO();
model.addAttribute("nameInfo", nameInfoDTO);

return "welcome-page";
}
@RequestMapping("/process-homepage")
public String showResultPage(NameInfoDTO nameInfoDTO, Model model) {
// writing the value to the properties
// by fetching from the URL
model.addAttribute("nameInfo", nameInfoDTO);
return "result-page";
}

And we can write this code using the @ModelAttribute annotation as follows:

@RequestMapping("/home")
public String showHomePage(@ModelAttribute("nameInfo") NameInfoDTO nameInfoDTO) {

return "welcome-page";

}
@RequestMapping("/process-homepage")
public String showResultPage(@ModelAttribute("nameInfo") NameInfoDTO nameInfoDTO) {
return "result-page";

}

So, we have noticed that we have converted this much of the code.

NameInfoDTO nameInfoDTO = new NameInfoDTO();
model.addAttribute("nameInfo", nameInfoDTO);

To a single line of code using @ModelAttribute Annotation

@ModelAttribute("nameInfo") NameInfoDTO nameInfoDTO

So, as the definition says "@ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute and then exposes it to a web view." Let's now run our application and see if everything is working fine or not. 

Run Your Application

To run our Spring MVC Application right-click on your project > Run As > Run on Server. And run your application as shown in the below image as depicted below as follows:  

Running the application

After that use the following URL to run your controller

http://localhost:8080/simple-calculator/geeksforgeeks.org/home

Output:

Output page1

So, in the output, you can see whenever you hit the URL the values are already present which means spring successfully read the values from the variable. Now let's put some values inside the label and click on the Bind Data. Suppose here we have put "Amiya" as First Name and "Rout" as Last Name and whenever we click on the "Bind Data" button an URL is generated as below

http://localhost:8080/simple-calculator/geeksforgeeks.org/process-homepage?firstName=Amiya&lastName=Rout

And you can see on the next page the values are displayed.

Output page2

So, our application is working fine. 


Next Article
Spring MVC @ModelAttribute Annotation with Example

A

AmiyaRanjanRout
Improve
Article Tags :
  • Java
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Spring MVC - Last 24 Hour Cryptocurrency Data using REST API
    Cryptocurrencies are a hot topic now and in the future; they may also be a payment source. Hence a lot of research is getting done. Many REST APIs are available to provide data in JSON format. We are going to see one such REST API as https://api.wazirx.com/sapi/v1/ticker/24hr?symbol=<Need to prov
    5 min read
    Spring MVC - Sample Project For Finding Doctors Online with MySQL
    Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. With MySQL as the backend, we can store all doctor details and by using Spring MVC function
    5 min read
    Spring MVC JSTL Configuration
    JavaServer Pages Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. Here we will be discussing how to use the Maven build tool to add JSTL support to a Spring MVC application. also, you'll learn how to act
    1 min read
    Spring MVC with MySQL - Sample Project For Calculating Electricity Bill
    Let us see a sample electricity bill calculation project by using Spring MVC + MySQL connectivity + JDBCTemplate. Additionally, let us test the same by using MockMvc + JUnit. MySQL Queries: DROP DATABASE IF EXISTS test; CREATE DATABASE test; USE test; DROP TABLE test.personsdetails; CREATE TABLE per
    7 min read
    Spring MVC - Comparison of Cryptocurrencies using REST API
    REST APIS is available in plenty nowadays. As cryptocurrencies are a hot topic nowadays, there is always a need to compare the different cryptocurrencies and get the corresponding value in different currencies. As a sample, let us take a REST API call as https://min-api.cryptocompare.com/data/price?
    6 min read
    Spring MVC - Get Probability of a Gender by Providing a Name using REST API
    A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call h
    7 min read
    Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API
    Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. In this article, we are going to see about a REST API call to find the coordinates for the
    6 min read
    Spring MVC with MySQL and Junit - Finding Employees Based on Location
    In real-world scenarios, organizations are existing in different localities. Employees are available in many locations. Sometimes they work in different 2 locations i.e. for a few days, they work on location 1 and for a few other days, they work on location 2. Let's simulate this scenario via MySQL
    8 min read
    Spring MVC - Get University/College Details via REST API
    REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applicat
    6 min read
    Spring MVC - JSTL forEach Tag with Example
    JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences