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<String,?> 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<String,?> 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.
8) asMap
It returns the current set of model attributes as a Map.
Map<String,Object> asMap()
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:
Java
package com.geeks.app; public class Details { private String name; private String lang; private String ide; public String getName() { return name; } public void setName(String name) { this .name = name; } public String getLang() { return lang; } public void setLang(String lang) { this .lang = lang; } public String getIde() { return ide; } public void setIde(String ide) { this .ide = ide; } } |
The ‘Details’ class has three attributes: name, lang, and ide and their getters/setters methods for all the properties to get and set the values.
2) DetailsController.java file:
Java
package com.geeks.app; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class DetailsController { @RequestMapping (value = "/" ) public String viewPage(Model model) { Details detail = new Details(); model.addAttribute( "detail" , detail); List<String> ideNames = Arrays.asList( "Eclipse" , "IntelliJ" , "PyCharm" , "Visual Studio" , "NetBeans" ); model.addAttribute( "ideNames" , ideNames); return "details" ; } @RequestMapping (value = "/submit" , method = RequestMethod.POST) public String submit( @ModelAttribute ( "detail" ) Details detail) { return "detailsSummary" ; } } |
This controller has a GET method mapped to ‘/’ and a POST method mapped to ‘/submit’.
Annotations used:
- @Controller conveys to the container that this class is the spring controller class. To use this annotation we need to import org.springframework.stereotype.Controller package.
- @RequestMapping, maps the request URLs to the specified method based on the value provided. To use this annotation, we need to import org.springframework.web.bind.annotation.RequestMapping package.
- @ModelAttribute, used to bind a method parameter or method return value to the named model attribute. We need to import org.springframework.web.bind.annotation.ModelAttribute package.
The ‘viewPage’ method returns the ‘detail’ form template. It includes the ‘detail’ model attribute so that the template can associate form attributes with a ‘detail’ object. And also, it includes ‘ideNames’ model attribute to display the values in the dropdown field which is mapped with the same name on the JSP page. The ‘submit’ method has the ‘Details’ object, it redirects the browser to the ‘detailsSummary’ page on POST request.
3) details.jsp file:
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!DOCTYPE html> < html > < head > < meta charset = "ISO-8859-1" > < title >Welcome Page</ title > </ head > < body > < h2 >Welcome to Lazyroar!!</ h2 > < h3 >Please fill in the form</ h3 > < form:form action = "submit" method = "post" modelAttribute = "detail" > < table > < tr > < td >< form:label path = "name" >Name: </ form:label ></ td > < td >< form:input path = "name" /></ td > </ tr > < tr > < td >< form:label path = "lang" >Coding Language: </ form:label ></ td > < td >< form:radiobutton path = "lang" label = "Java" value = "Java" /> < form:radiobutton path = "lang" label = "C Language" value = "C Language" /> < form:radiobutton path = "lang" label = "Python" value = "Python" /></ td > </ tr > < tr > < td >< form:label path = "ide" >Select IDE: </ form:label ></ td > < td >< form:select path = "ide" items = "${ideNames}" /></ td > </ tr > < tr > < td >< form:button >Submit</ form:button ></ td > </ tr > </ table > </ form:form > </ body > </ html > |
The page contains a simple form, with each of its fields in a separate cell in a table. The form is geared to post to ‘/submit’. It is marked as being backed up by the ‘details’ model attribute and to the ‘POST’ method – ‘submit’ in the web controller. We are using Spring form’s tag library to display the label names, input fields, dropdown, and radio button tags. In the dropdown field, we are using the placeholder ‘${ideNames}’, in which once the application runs, this holder object will be updated with the data provided in the ‘ideNames’ model attribute in the controller class.
4) detailsSummary.jsp file:
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> < html > < head > < meta charset = "ISO-8859-1" > < title >Summary page</ title > </ head > < body > < h3 >Details submitted!</ h3 > < table > < tr > < td >Name:</ td > < td >${detail.name}</ td > </ tr > < tr > < td >Coding Language:</ td > < td >${detail.lang}</ td > </ tr > < tr > < td >IDE selected:</ td > < td >${detail.ide}</ td > </ tr > </ table > </ body > </ html > |
This is the result JSP page to display the user entered values in the browser after the processing of the input. Each field will be displayed in a separate cell in a table.
Run the Application:
- Right-click on the Project, Run as -> Run on Server.
- Select the server in the localhost to run the application.
- Open the URL: http://localhost:8080/app/ in the browser to get the below screen.
- Input the details in the form.
- Click on submit to get the output.