Spring Model Interface

Facebooktwitterredditpinterestlinkedinmailby feather

Model Interface

Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available in the org.springframework.ui package.

The Model interface acts as a data container that contains the data of the MVC application. The stored data can of any form such as String, Object, etc.

Following are some methods of the Model interface:

Method Description
Model addAllAttributes(Collection<?> attributeValues) It copies all the attributes in the provided Collection into this Map.
Model addAllAttributes(Map<String,?> attributes) It copies all the attributes in the provided Map into this Map.
Model addAttribute( Object attributevalue) It adds the given attribute to this Map through a generated name.
Model addAttribute(String attributeName, Object attributeValue ) It wraps the given attributes with the given name.
Map<String, Object> asMap() It returns a current set of model attributes as a Map.
Boolean containsAttribute(String attributeName) It searches whether the model contains the attribute of the given name.
Model mergeAttributes(Map<String,?> attributes) It copies all the attributes in the given Map into this Map, with the existing objects of the same name.

Example of Model interface

Following are the steps to create an example of adding form data to the Model object:

  1. Create a web request page

In this step, we are going to create a request page named index.jsp, which contains the link to other view pages.

index.jsp

  • Create the Controller class

In this step, we are going to create a controller class named MainController.java, which returns the JSP view pages. Here, we are using the HttpServletRequest interface that provides request information for HTTP servlets.

MainController.java

  • Add the entry of Controller into web.xml

In this step, we are going to add the entry of the Controller into a web.xml file.

web.xml

  • Define bean into another XML file.

In this step, we are going to declare the bean inside another XML file (spring-servlet.xml).

spring-servlet.xml

  • Create other JSP pages.

In this step, we are going to create the other JSP view pages.

genform.jsp

formdata.jsp

Output

Following are the outputs of the application:

Spring Model Interface
Spring Model Interface 1
Spring Model Interface 2
Spring Model Interface 3
Facebooktwitterredditpinterestlinkedinmailby feather