The Wayback Machine - https://web.archive.org/web/20240709210702/https://www.geeksforgeeks.org/how-to-create-your-first-model-in-spring-mvc/
Open In App

How to Create Your First Model in Spring MVC?

Last Updated : 07 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring MVC is a Web MVC Framework for building web applications. The Spring MVC framework is comprised of the following components:

  • Model: A model can be an object or collection of objects which basically contains the data of the application.
  • View: A view is used for displaying the information to the user in a specific format. Spring supports various technologies like freemarker, velocity, and thymeleaf.
  • Controller: It contains the logical part of the application. @Controller annotation is used to mark that class as controller.
  • Front Controller: It remains responsible for managing the flow of the web application. DispatcherServlet acts as a front controller in Spring MVC.

As we have already discussed the Controller part of figuring out how we can create and Run Your First Spring MVC Controller and the View part of How to Create Your First View in Spring MVC. Now we have only left the Model part. So in this article, we will be creating our First Model in Spring MVC using Spring Tool Suite IDE. 

Note: Models are nothing, they are just data. 

Pre-requisite: Prior to it, certain requirements are needed that are as follows:  

  1. Eclipse (EE version)/STS IDE
  2. Spring JAR Files
  3. Tomcat Apache’s latest version

Note: We are going to use Spring Tool Suite 4 IDE for this project. Please do go through how to download and install Spring Tool Suite for Eclipse IDE

Implementation: It is illustrated below step by step as follows:

Configuring Dispatcher Servlet

Note: One should be well aware of what is Dispatcher Servlet in Spring as it is a crucial concept to understand prior adhering ahead. 

Now we are going to configure Dispatcher Servlet with our Spring MVC application. 

Step 4: Go to the src > main > webapp > WEB-INF > web.xml file.

File: web.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    id="WebApp_ID" version="4.0">
    <display-name>springmvc-view-resolver</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.jsp</welcome-file>
        <welcome-file>default.htm</welcome-file>
    </welcome-file-list>
  
    <absolute-ordering />
  
    <servlet>
        <!-- Provide a Servlet Name -->
        <servlet-name>viewresolver-dispatcher</servlet-name>
        <!-- Provide a fully qualified path to the DispatcherServlet class -->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
  
    <servlet-mapping>
        <!-- Provide a Servlet Name that you want to map -->
        <servlet-name>viewresolver-dispatcher</servlet-name>
        <!-- Provide a url pattern -->
        <url-pattern>/demo.com/*</url-pattern>
    </servlet-mapping>
  
</web-app>


Step 5: Now go to the  src > main > webapp > WEB-INF and create an XML file. Actually, this is a Spring Configuration file like the beans.xml file. And the name of the file must be in this format.

YourServletName-servlet.xml  

For example: For this project, the name of the file must be

viewresolver-dispatcher-servlet.xml 

So either you can create a Spring Configuration File or you can just create a simple XML file and add the below lines of code inside that file.

File: viewresolver-dispatcher-servlet.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    
  <!-- This Line is used for scanning all the packages that have controller classes -->
  <context:component-scan base-package="com.demo.controllers"></context:component-scan>
  
</beans>


Creating Spring MVC Controller

Step 6: Now, let’s create some controllers. Go to the src/main/java and create a new controllers package (For ex. com.demo.controllers) as per your choice. And inside that create a Java class and name the class as DemoController. Now how to tell the Spring that this is our controller class. So the way we are going to tell the Spring is by marking it with a @Controller annotation.

@Controller
public class DemoController {}

Note: Spring will automatically initialize the class having a @Controller annotation and register that class with the spring container.

Now let us create a simple method inside the Controller class and use the @RequestMapping annotation before the method something like this.

// Annotation 
@RequestMapping("/hello")

// Method 
public String helloWorld() 
{
    return "";
}

Now in the return statement, we have to return some views (web pages), so whenever the endpoint ‘/hello’ is invoked we can see our result on the web page. So let’s create our first View.

Creating View

Go to the src > main > webapp > WEB-INF > right-click > New > Folder and name the folder as views. Then views > right-click > New > JSP File and name your first view. Here we have named it as demo.jsp file. Below is the code for the demo.jsp file. We have created a simple web page inside that file. 

File: demo.jsp

HTML




<!DOCTYPE html>
<html>
<body>
    <h1 align="center">GeeksforGeeks Welcome Page!</h1>
</body>
</html>


Now go to the DemoController class and inside the helloWorld() method we have to return a value something like this.

return "demo";

File: DemoController.java 

Java




// Java Program to Illustrate DemoController Class
  
package com.demo.controllers;
  
// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
  
// Class
@Controller
public class DemoController {
  
    // Method
    @RequestMapping("/hello") public String helloWorld()
    {
        // Just return the page name
        // No Path, no extension
        return "demo";
    }
}


Creating First Model

Now we are going to create our first Model inside our spring MVC application. We are going to send data to the view (jsp page) from the controller handler methods. So now let’s create a String value using String literal something like this

String myName = "Amiya Rout";

And here we are going to send this “myName” data to the jsp page. And we can do it using the Model interface which is present inside the “org.springframework.ui.Model” package in Spring. We can write the code something like this

public String helloWorld(Model model) {
    // Sending data to view (jsp page)
    String myName = "Amiya Rout";
    model.addAttribute("myNameValue", myName);
}

The complete code for DemoController.java is given below.

File: DemoController.java 

Java




// Java Program to Illustrate DemoController Class 
  
package com.demo.controllers;
  
// Importing required classes 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
  
// Class 
@Controller
public class DemoController {
  
    // Method 
    @RequestMapping("/hello")
    public String helloWorld(Model model) {
        
        // Sending data to view (jsp page)
        String myName = "Amiya Rout";
        model.addAttribute("myNameValue", myName);
          
        // Just return the page name
        // No Path, no extension
        return "demo";
    }
  
}


And to display the data inside our jsp page we have to modify the demo.jsp page. And we can do it by the following line of code

${myNameValue}

Now the complete code for Demo.jsp is given below and you are done. Now, let us run the application. 

HTML




<!DOCTYPE html>
<html>
<body>
    <h1 align="center">GeeksforGeeks Welcome Page!</h1>
    <hr>
    My name is: ${myNameValue}
</body>
</html>


Run Spring MVC Application

Step 8: To run your Spring MVC Application right-click on your project > Run As > Run on Server and run your application as shown in the below image. 

After that use the following URL to run your controller

http://localhost:8080/springmvc-view-resolver/demo.com/hello

Output:

Output

 



Previous Article
Next Article

Similar Reads

Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using maps. In this article, we will see how to set up a Spring
5 min read
How to Create Your First View in Spring MVC?
Spring MVC is a Web MVC Framework for building web applications. The Spring MVC framework is comprised of the following components: Model: A model can be an object or collection of objects which basically contains the data of the application.View: A view is used for displaying the information to the user in a specific format. Spring supports variou
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
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 h
7 min read
Model, ModelMap, ModelAndView in Spring MVC
Spring is one of the most used Java-based frameworks for creating enterprise-grade applications in Java. In that Spring MVC was one of the popular projects under the Spring family of Java projects. In this article, we will explore how Model, ModelMap, and ModelAndView work in Spring MVC. Spring MVC follows the Model-View-Controller (MVC) pattern to
7 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Controller, and seamlessly handles the application in
3 min read
Difference Between Spring MVC and Spring WebFlux
Spring MVCSpring MVC Framework takes on the Model-View-Controller design pattern, which moves around the Dispatcher Servlet, also called the Front Controller. With the help of annotations like @Controller and @RequestMapping, the by-default handler becomes a robust(strong) tool with a diverse set of handling ways. This kind of dynamic kind of featu
5 min read
Spring MVC vs Spring Web Flux: Top Differences
For creating Java-based projects and applications, developers usually have to choose between Spring MVC and Spring WebFlux when using the Spring framework to create web apps. To pick the best framework for their project, developers need to know how each one is different and what features they have. Each framework has its own benefits compared to th
11 min read
How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt
3 min read
Spring MVC - Create Registration Form using Form Tag Library
Spring Framework provides spring’s form tag library for JSP views in Spring’s Web MVC framework. In Spring Framework, we use Java Server Pages(JSP) as a view component to interact with the user. From version 2.0, Spring Framework provides a comprehensive set of data binding-aware tags. These tags are used for handling form elements when using JSP a
7 min read
Practice Tags :
three90RightbarBannerImg