Spring @ModelAttribute Annotation Example
In spring, the @ModelAttribute
annotation populates the model data or the method parameters even before the handler method is invoked or called. In this tutorial, we will show how to implement the Spring @ModelAttribute Annotation with the Spring MVC framework.
1. Introduction
1.1 Spring Framework
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring Mvc Framework
Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:
- Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a
POJO
class which encapsulates the application data given by the controller - View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the
JSP
templates written with Java Standard Tag Library (JSTL
) - Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet
1.3 Spring @ModelAttribute Annotation
The @ModelAttribute
annotation refers to the property of the Model object and is used to prepare the model data. This annotation binds a method variable or the model object to a named model attribute. The annotation accepts an optional value
which indicates the name of the model attribute. If no value
attribute is supplied then,
- Either the value would default to the return type name in case of the methods
- Or, parameter type name in case of the method variables
The @ModelAttribute
annotation can be used at the parameter level or the method level. The use of this annotation at the parameter level is to accept the request form values while at the method level is to assign the default values to a model. Let me explain you further with the help of some examples.
1.3.1 @ModelAttribute annotation at Parameter level
When using the @ModelAttribute
annotation as a method parameter, it binds the form data with a POJO bean. It has a value
attribute which acts as a name of the model attribute to bind. This is what the code snippet looks like:
Code snippet
@RequestMapping(value="/handleRequest", method=RequestMethod.GET) public ModelAndView handleRequest(@ModelAttribute(value="userObj") User user) { user.setName("Java Code Geek"); return new ModelAndView("myView"); }
In this case, a new instance of the userObj
is created and then passed to the handler method for further processing. Make note, if the User
object is an Interface or an Abstract class, then a BeanInstantiationException
will be thrown.
1.3.2 @ModelAttribute annotation at Method level
When using the @ModelAttribute
annotation at the method level, developers can add the values in the Model at a global level. It means for every request, a default value will be there in the controller for every response. This is what the code snippet looks like:
Code snippet
@ModelAttribute public void addAttributes(Model model) { model.addAttribute("welcome_text", "Welcome to the application page."); }
Now, open up the Eclipse IDE and let’s see how to use the @ModelAttribute
annotation in the spring framework!
2. Spring @ModelAttribute Annotation Example
Here is a step-by-step guide for implementing this annotation in the spring mvc framework.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the Maven Web App archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring.modelattribute</groupId> <artifactId>SpringModelAttribute</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
We can start adding the dependencies that developers want like Servlet API, Spring Mvc etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the spring mvc framework. The rest dependencies such as Spring Beans, Spring Core etc. will be automatically resolved by Maven. The updated file will have the following code:
pom.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.spring.modelattribute</groupId> <artifactId>SpringModelAttribute</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringModelAttribute Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.6.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> </dependencies> <build> <finalName>SpringModelAttribute</finalName> </build> </project>
3.2 Configuration Files
Let’s write all the configuration files involved in this application.
3.2.1 Web Deployment Descriptor
The web.xml
file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>SpringModelAttribute</display-name> <servlet> <servlet-name>modelattributedispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>modelattributedispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.2.2 Spring Configuration File
To configure the spring framework, developers need to implement a bean configuration file i.e. modelattributedispatcher-servlet.xml
which provide an interface between the basic Java class and the outside world. Add the following code to it:
modelattributedispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.spring.mvc.model.attribute" /> <!-- this is used by the dispatcher servlet to render the particular view page --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
Do note:
- This file is loaded by the spring’s Dispatcher Servlet which receives all the requests coming into the application and dispatches them to the controller for processing
- This file has the
InternalResourceViewResolver
bean declaration that tells the framework how to find the physicalJSP
files according to the logical view names returned by the controllers, by attaching the prefix and the suffix to a view name
3.3 Java Class Creation
Let’s create a simple class where the @Controller
annotation specifies this class as a spring controller and is responsible for handling the incoming request. In here the method parameter is annotated with the @ModelAttribute
annotation. Add the following code to it:
ModelController.java
package com.spring.mvc.model.attribute; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; 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.servlet.ModelAndView; @Controller public class ModelController { @ModelAttribute(name= "countrieslist") public List<String> populateCountries() { List<String> countries= new ArrayList<String>(); countries.add("India"); countries.add("United States"); countries.add("Japan"); countries.add("Australia"); countries.add("Canda"); return countries; } @RequestMapping(value= "/init", method= RequestMethod.GET) public ModelAndView initView(@ModelAttribute(name= "countrieslist") List<String> countries) { ModelAndView modelview = new ModelAndView(); modelview.addObject("message", "This is an example of using the @ModelAttribute annotation .....!"); modelview.setViewName("output"); return modelview; } }
3.4 JSP View
Spring Mvc supports many types of views for different presentation technologies. These include – JSP
, HTML
, XML
etc. So let us write a simple result view in SpringModelAttribute/src/main/webapp/WEB-INF/views
.
3.4.1 Output Page
This is the welcome page of this example demonstrating the usage of the @ModelAttribute
annotation in the spring mvc framework. Add the following code to it:
output.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> <%@ page isELIgnored="false" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Model Attribute Example</title> </head> <body> <h2>@ModelAttribute example</h2> <hr /> <div id="welcome_message">${message}</div> <div> </div> <table> <tr> <td>Countries: ${countrieslist}</td> </tr> </table> </body> </html>
4. Run the Application
As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.
5. Project Demo
Open your favorite browser and hit the following URL to display the output page.
http://localhost:8082/SpringModelAttribute/
Server name (localhost) and port (8082) may vary as per your tomcat configuration.
That’s all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and don’t forget to share!
6. Conclusion
In this section, developers learned how the @ModelAttribute
annotation can be used to pre-populate the model data even before the handler method is called. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of Spring @ModelAttribute Annotation.
You can download the full source code of this example here: SpringModelAttribute