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.

Example:

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.


            com.fasterxml.jackson.core
            jackson-databind
             2.4.1
 
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:
pom.xml


  4.0.0
  com.arpit.java2blog
  SpringRestfulWebServicesWithJSONExample
  war
  0.0.1-SNAPSHOT
  SpringRestfulWebServicesWithJSONExample Maven Webapp
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    
    
   javax.servlet
   javax.servlet-api
   3.1.0
  

  
   org.springframework
   spring-core
   ${spring.version}
  
  
   org.springframework
   spring-webmvc
   ${spring.version}
  
   
            com.fasterxml.jackson.core
            jackson-databind
             2.4.1
        
 
 
  SpringRestfulWebServicesWithJSONExample

  
   
    org.apache.maven.plugins
    maven-compiler-plugin
    3.1
    
     ${jdk.version}
     ${jdk.version}
    
   
  

 
 
  4.2.1.RELEASE
  1.7
 

Spring application configuration:

3) Change web.xml as below:



 Archetype Created Web Application
  
   index.jsp

  
 
 springrest
 
  org.springframework.web.servlet.DispatcherServlet
 
 1



 springrest
 /


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.



 

 
  
   /WEB-INF/
  
  
   .jsp
  
 
 

Create bean class

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

package org.arpit.java2blog.bean;

public class Country{

 String countryName;
 long population;

 public Country() {
  super();
 }
 public Country(String countryName,long population) {
  super();
  this.countryName = countryName;
  this.population=population;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 }

}

Create Controller

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

package org.arpit.java2blog.controller;

import org.arpit.java2blog.bean.Country;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CountryController {

 @ModelAttribute
 public Country getCountry(@RequestParam String countryName, @RequestParam  long population)
 {
  Country country=new Country();
  country.setCountryName(countryName);
  country.setPopulation(population);
  return country;
 }
 @RequestMapping(value = "/addCountry", method = RequestMethod.POST)
 public String addCountry(@ModelAttribute Country country,ModelMap model) {
  model.addAttribute("countryName", country.getCountryName());
  model.addAttribute("population", country.getPopulation());
  return "countryDetails";
 }
}
Create view

Modify index.jsp as below





Add Country
Country
Population
Create countryDetails.jsp in /WEB-INF/ folder
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Country Details


  Added country :
 

Country Name: ${countryName}

Population : ${population}

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.