Spring MVC – Model Interface
The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework – Dependency Injection. It is designed around a ‘DispatcherServlet’ that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, and theme resolution as well as support for uploading files. In the MVC framework, M stands for Model – used to work with the data, V stands for View – used to work with presenting data to user and C stands for Controller – that contains actual business logic to process the user input.
Spring Framework provides an Interface called Model(I) to work with the data. It defines a placeholder for model attributes and is primarily designed for adding attributes to the model. It is also used to transfer data between the view and controller of the Spring MVC application. Model interface is available in the org.springframework.ui package. It acts as a data container that contains the data of the application. That stored data can be of any form such as String, Object, data from the Database, etc.
Methods Available in Model(I)
Below are the methods available in Model(I).
1) addAttribute
It adds the specified attribute under the supplied name.
Model addAttribute(String attributeName, @Nullable Object attributeValue) attributeName - the name of the model attribute - can never be null attributeValue - the model attribute value - can be null
2) addAttribute
It adds the specified attribute to this Map using a generated name.
Model addAttribute(Object attributeValue) attributeValue - the model attribute value - can never be null
3) addAllAttributes
To copy all the attributes in the specified Collection into this Map, using attribute-name generation for each element.
Model addAllAttributes(Collection attributeValues) attributeValues - the model attribute values
4) addAllAttributes
To copy all the attributes in the supplied Map into this Map.
Model addAllAttributes(Map attributes)
5) mergeAttributes
To copy all the attributes in the supplied Map into this Map, with existing objects of the same name taking precedence, that is, they are not getting replaced.
Model mergeAttributes(Map attributes)
6) containsAttribute
To check whether this model contains an attribute of the given name?
boolean containsAttribute(String attributeName) attributeName - the name of the model attribute - not null It returns the value true/false.
7) getAttribute
To return the attribute value for the specified name, if present.
@Nullable Object getAttribute(String attributeName) attributeName - the name of the model attribute - not null It returns the corresponding attribute value. If not, it returns null.
It returns the current set of model attributes as a Map.
Spring MVC Application
We will create a simple Spring MVC application in Spring Tool Suite (STS) on how to use Model objects in holding the form data.
Steps to create the application:
- Create a Spring MVC project in Spring Tool Suite.
- In STS while creating the project based on the developer selection, it will download all the required maven dependencies, *.jar, lib files and it will provide an embedded server.
- We can see all the dependencies that are required are available in the ‘pom.xml’ file.
- Create a Bean class, Controller class, and the JSP view pages.
- Below is the final project structure of the Spring MVC project after creating *.java and *.jsp files.
Implementation:
Files to be created are as follows:
- Details.java – Bean class – To define the field properties and getter/setter methods of the properties.
- DetailsController.java – Controller class – To process the user request and generate the output.
- details.jsp – JSP file to interact with the user for the input.
- detailsSummary.jsp – JSP file to display the output to the user after processing the input.
1) Details.java file:
Spring Boot Model
Spring Boot Model tutorial shows how to work with a model in a Spring Boot application. The model is represented by Model , ModelMap , and ModelAndView in Spring.
is a popular Java application framework and is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily.
MVC
is a software architecture pattern, which separates application into three parts: model, view, and controller. The model represents a Java object carrying data. The view visualizes the data that the model contains. The controller manages the data flow into model object and updates the view whenever data changes; it keeps view and model separate.
Spring MVC
is the original web framework built on the Servlet API. It is build on the MVC design pattern. Spring Framework 5.0 introduced a parallel reactive stack web framework called Spring WebFlux.
Model, ModelMap, ModelAndView
Model , ModelMap , and ModelAndView are used to define a model in a Spring MVC application. Model defines a holder for model attributes and is primarily designed for adding attributes to the model. ModelMap is an extension of Model with the ability to store attributes in a map and chain method calls. ModelAndView is a holder for a model and a view; it allows to return both model and view in one return value.
Spring Boot Model example
The following simple web application uses Model , ModelMap , and ModelAndView in the controller methods. The model holds application data, which is displayed in the view. We use the Freemaker library for the view layer.
build.gradle . src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── Application.java │ │ └── controller │ │ └── MyController.java │ └── resources │ ├── application.properties │ ├── static │ │ └── index.html │ └── templates │ └── show.ftlh └── test ├── java └── resources
This is the project structure of the Spring application.
plugins < id 'org.springframework.boot' version '2.6.7' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' >group = ‘com.example’ version = ‘0.0.1-SNAPSHOT’ sourceCompatibility = ’17’ repositories < mavenCentral() >dependencies
This is the Gradle build file.
spring.main.banner-mode=off spring.main.log-startup-info=false mymessage=Hello there
The application.properties is the main configuration file in Spring Boot. We turn off the Spring banner and startup logging of the Spring framework. The mymessage property contains the message.
package com.zetcode.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Locale; @Controller public class MyController < @Value("$") private String message; @GetMapping("/getMessage") public String getMessage(Model model) < model.addAttribute("message", message); return "show"; >@GetMapping("/getMessage2") public ModelAndView getMessage() < var mav = new ModelAndView(); mav.addObject("message", message); mav.setViewName("show"); return mav; >@GetMapping("/getMessageAndTime") public String getMessageAndTime(ModelMap map) < var ldt = LocalDateTime.now(); var fmt = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM); fmt.withLocale(new Locale("sk", "SK")); fmt.withZone(ZoneId.of("CET")); String time = fmt.format(ldt); map.addAttribute("message", message).addAttribute("time", time); return "show"; >>
This is MyController . It has three methods that respond to client requests.
@Controller public class MyControllerMyController is annotated with the @Controller annotation.
@Value("$") private String message;With the @Value annotation, we insert the mymessage property from the application.properties file into the message attribute.
@GetMapping("/getMessage") public String getMessage(Model model)
The @GetMapping maps the /getMessage URL pattern to the getMessage() method. In the getMessage() method, we use the Model . It receives a message attribute with the addAttribute() method. The return keyword returns the name of the view, which will be resolved to show.ftl , because we use the Freemarker template system.
@GetMapping("/getMessage2") public ModelAndView getMessage()
In the second case, we use the ModelAndView . We use addObject() and setViewName() to add the model data and the view name. The method returns ModelAndView object.
@GetMapping("/getMessageAndTime") public String getMessageAndTime(ModelMap map)
In the getMessageAndTime() method, we use ModelMap . The model map receives two attributes: message and time.
This is the home page. It contains three links that call the Spring controller methods. It is a static resource and is located in the predefined src/main/resources/static directory.
Message: $ <#if time??>
Date and time: $#if>
The show.ftlh is a Freemarker template file. It is located in the predefined src/main/resources/templates directory. It outputs the message and optionally the time with the $<> syntax.
package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application < public static void main(String[] args) < SpringApplication.run(Application.class, args); >>Application is the entry point which sets up Spring Boot application.
After we start the application, we navigate to localhost:8080 .
In this tutorial, we have have worked with a model in a Spring application.