Spring MVC @ModelAttribute example


@ModelAttribute is one of most important Spring MVC annotation.

Spring MVC tutorial:

@ModelAttribute is used to bind request parameters with model object.  Lets say you have 10 request parameters , you can wrap them to model object and pass it in the to handler method.

There are two ways to create model object.
  • Object is already present in session or ModelMap object.
  • Annotate another method with @ModelAttribute annotation and create the model object. This method will get called before actual handler call.


Source code:

click to begin

20KB .zip

Here are steps to create a Spring MVC ModelAttribute example.

1) Create a dynamic web project using maven in eclipse named “SpringMVCModelAttributeExample”

Maven dependencies

2) We need to add Jackson json utility in the classpath.

Spring will load Jackson2JsonMessageConverter into its application context automatically. Whenever you request resource as json with accept headers=”Accept=application/json”, then Jackson2JsonMessageConverter comes into picture and convert resource to json format.

Now change pom.xml as follows:

Spring application configuration:

3) Change web.xml as below:

4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.

Create bean class

5) Create a bean name “Country.java” in org.arpit.java2blog.bean.

Create Controller

6) Create a controller named “CountryController.java” in package org.arpit.java2blog.controller

Modify index.jsp as below

Create countryDetails.jsp in /WEB-INF/ folder

7) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

Maven build in eclipse
8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

10) You will see screen as below:

Spring MVC model attribute example

11) When you click on submit button , you will see below screen.


Add Comment