Javatpoint Logo
Javatpoint Logo

Spring MVC Model Interface

In Spring MVC, the model works a container that contains the data of the application. Here, a data can be in any form such as objects, strings, information from the database, etc.

It is required to place the Model interface in the controller part of the application. The object of HttpServletRequest reads the information provided by the user and pass it to the Model interface. Now, a view page easily accesses the data from the model part.

Methods of Model Interface

Method Description
Model addAllAttributes(Collection<?> arg) It adds all the attributes in the provided Collection into this Map.
Model addAllAttributes(Map<String,?> arg) It adds all the attributes in the provided Map into this Map.
Model addAllAttribute(Object arg) It adds the provided attribute to this Map using a generated name.
Model addAllAttribute(String arg0, Object arg1) It binds the attribute with the provided name.
Map<String, Object> asMap() It return the current set of model attributes as a Map.
Model mergeAttributes(Map< String,?> arg) It adds all attributes in the provided Map into this Map, with existing objects of the same name taking precedence.
boolean containsAttribute(String arg) It indicates whether this model contains an attribute of the given name

Spring MVC Model Example

Let's create a login page that contains a username and password. Here, we validate the password with a specific value.

1. Add dependencies to pom.xml

2. Create the request page

Here, we create the login page to receive name and password from the user.

index.jsp

3. Create the controller class

In controller class:

  • The HttpServletRequest is used to read the HTML form data provided by the user.
  • The Model contains the request data and provides it to view page.

HelloController.java

4. Provide the entry of controller in the web.xml file

web.xml

5. Define the bean in the xml file

spring-servlet.xml

6. Create the other view components

To run this example, the following view components must be located inside the WEB-INF/jsp directory.

viewpage.jsp

errorpage.jsp

Output:

Spring MVC Model Interface
Spring MVC Model Interface
Spring MVC Model Interface
Spring MVC Model Interface
Spring MVC Model Interface




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA