The Wayback Machine - https://web.archive.org/web/20241126185919/https://www.geeksforgeeks.org/spring-mvc-framework/
Open In App

Spring – MVC Framework

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Spring MVC Framework follows the Model-View-Controller architectural design pattern which works around the Front Controller i.e. the Dispatcher Servlet. The Dispatcher Servlet handles and dispatches all the incoming HTTP requests to the appropriate controller. It uses @Controller and @RequestMapping as default request handlers. The @Controller annotation defines that a particular class is a controller. @RequestMapping annotation maps web requests to Spring Controller methods. The terms model, view, and controller are as follows:

  • Model: The Model encapsulates the application data.
  • View: View renders the model data and generates HTML output that the client’s browser can interpret.
  • Controller: The Controller processes the user requests and passes them to the view for rendering.

If you’re interested in mastering this pattern within Spring Boot, the Java Backend course will prepare you for common interview scenarios, ensuring you can discuss MVC principles confidently.

Dispatcher Servlet

Dispatcher Servlet is the front controller that manages the entire HTTP request and response handling process. Now, the question is What is Front Controller? It is quite simple, as the name suggests, when any web requests are made, the requests will come first to the front Controller which is nothing but the Dispatcher Servlet. The Front Controller stands first that is why it’s name is like this. After the requests comes into this, the dispatcher servlet accepts the requests and decides which controller will be suitable to handle these requests. Then it dispatches the HTTP requests to specific controller.

Spring Model-View-Controller Flow Diagram

Spring-MVC-Framework-Control-flow-Diagram

Spring MVC Framework works as follows:

  1. All the incoming requests are intercepted by the DispatcherServlet that works as the front controller.
  2. The DispatcherServlet then gets an entry of handler mapping from the XML file and forwards the request to the controller.
  3. The object of ModelAndView is returned by the controller.
  4. The DispatcherServlet checks the entry of the view resolver in the XML file and invokes the appropriate view component.

Advantages of Spring MVC Framework

  • The container is used for the development and deployment of applications and uses a lightweight servlet.
  • It enables rapid and parallel development.
  • Development of the application becomes fast.
  • Easy for multiple developers to work together.
  • Easier to Update the application.
  • It is Easier to Debug because we have multiple levels in the application.

Disadvantages of Spring MVC Framework

  • It has high complexity to develop the applications using this pattern.
  • It is not suitable for small applications which affect the application’s performance and design.

Create Your First Spring MVC Application

Consider the following example:

Step 0: Setup your project with maven use the required archtype to get the required folders directory and configure the server with your project.
Step 1: Load the spring jar files or add the dependencies if Maven is used. Add the following dependencies in pom.xml

pom.xml

XML
<project xmlns="http://maven.apache.org/POM/4.0.0" \
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.javatpoint</groupId>  
  <artifactId>SpringMVC</artifactId>  
  <packaging>war</packaging>  
  <version>0.0.1-SNAPSHOT</version>  
  <name>SpringMVC Maven Webapp</name>  
  <url>http://maven.apache.org</url>  
  <dependencies>  
    <dependency>  
      <groupId>junit</groupId>  
      <artifactId>junit</artifactId>  
      <version>3.8.1</version>  
      <scope>test</scope>  
    </dependency>  
      
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
    <dependency>  
      <groupId>org.springframework</groupId>  
      <artifactId>spring-webmvc</artifactId>  
      <version>5.1.1.RELEASE</version>  
    </dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
    <dependency>    
      <groupId>javax.servlet</groupId>    
      <artifactId>servlet-api</artifactId>    
      <version>3.0-alpha-1</version>    
    </dependency>  
  
  </dependencies>  
  <build>  
    <finalName>SpringMVC</finalName>  
  </build>  
</project>  

Step 2: Defining a Controller

Let us Create the Controller Class

HelloGeek.java

Java
@Controller  
public class HelloGeek {  
@RequestMapping("/")  
    public String display()  
    {  
        return "hello";  
    }     
}  


Step 3: Provide the name of the controller in the web.xml file as follows:
DispatcherServlet is the front controller in Spring Web MVC. Incoming requests for the HTML file are forwarded to the DispatcherServlet.

web.xml

XML
<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  


Step 4: We have to define the bean in a separate XML file. We have specified the view components in this file.  It is located in the WEB-INF directory.

spring-servlet.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.example.controller"/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

In this configuration,

  • We have added the necessary XML namespaces and schema locations.
  • <context:component-scan> tells Spring where to look for annotated components.
  • <mvc:annotation-driven> enables Spring MVC annotations.
  • The InternalResourceViewResolver bean is defined to resolve view names. It looks for JSP files in the /WEB-INF/views/ directory and appends .jsp to the view name.

Step 5: Use JSP to display the message

index.jsp:

HTML
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Spring MVC Example</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>


This JSP file will display the message passed from the controller.

Step 6: Start the server and run the project. The output is displayed as follows:

Spring MVC Tutorial!!




Previous Article
Next Article

Similar Reads

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
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
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
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
How to Build a RESTful API with Spring Boot and Spring MVC?
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTful API using Spring Boot and Spring MVC. We will w
7 min read
Spring MVC – Handling Form Validation with Spring Validator
Form validation is crucial in web applications to ensure that user input is both accurate and appropriate before processing or storing it. In Spring MVC, form validation can be efficiently managed using the Spring Validator interface and annotations. This allows for flexible and robust validation mechanisms that are easy to implement and maintain i
7 min read
Securing a Spring MVC Application with Spring Security
Securing web applications is crucial in today's world, where security threats are prevalent. Spring Security is a powerful, customizable authentication and access-control framework that is part of the larger Spring ecosystem. It helps secure Spring MVC applications by managing authentication, authorization, and other security concerns. This article
7 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
Spring Boot - Reactive Programming Using Spring Webflux Framework
In this article, we will explore React programming in Spring Boot, Reactive programming is an asynchronous, non-blocking programming paradigm for developing highly responsive applications that react to external stimuli. What is Reactive ProgrammingIn reactive programming, the flow of data is asynchronous through push-based publishers and subscriber
4 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Migrating a Spring Boot Application from Spring Security 5 to Spring Security 6
Spring Security is a powerful authentication and access control framework for Java applications specially for those built with the Spring Framework. With the release of Spring Security 6, several enhancements and changes have been introduced to simplify the security configuration and provide better performance and security features. This article ai
4 min read
Data Transfer Object (DTO) in Spring MVC with Example
In Spring Framework, Data Transfer Object (DTO) is an object that carries data between processes. When you're working with a remote interface, each call is expensive. As a result, you need to reduce the number of calls. The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across
8 min read
Spring MVC - Get Probability of a Gender by Providing a Name using REST API
A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call https://api.genderize.io?name=<Provide your desi
7 min read
Spring - MVC Regular Expression Validation
Regular Expression Validation in Spring MVC can be achieved by using Hibernate Validator which is the implementation of Bean Validation API. Hibernate Validator provides @Pattern annotation which is used for regular expression validation. Syntax: @Pattern(regex="", flag="", message="") private String someDataMember; Note that the flag and message a
4 min read
Spring MVC using Java based configuration
Prerequisites: MVC Design Pattern, Spring MVC with JSP ViewSpring 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
5 min read
Spring MVC - Get Exchange Rate Values using REST API
People are doing business, and developing software for geographical locations. That means the calculation of a software price will vary globally. During those scenarios, we need to know about the exchange rates for a given currency. Nowadays many open source REST API calls are available and among that there is a call available to get exchange rates
5 min read
Spring - MVC Form Drop-Down List
In this article, we will learn about the Spring MVC Dropdown list. We will create a basic Spring MVC project in Spring tool suite(STS) to make a dropdown list using form:select tag. spring-form.tld We can use Java Server Pages (JSPs) as a view component in Spring Framework. To help you implement views using JSP, the Spring Framework provides form t
7 min read
Spring - MVC Validation
The Spring MVC framework provides us with standard predefined validators to validate user input data in a simple and straightforward way. The Bean Validation API is the popular approach for data validations in Spring applications. Here we will be using the hibernate implementation of the Bean Validation API known as Hibernate Validator. Validation
5 min read
Spring - MVC TextArea
Here we will be learning about the Spring MVC TextArea form tag. We will create a basic Spring MVC project in the Spring tool suite(STS) to get some data from the user using the TextArea form tag. spring-form.tld We can use Java Server Pages (JSPs) as a view component in Spring Framework. To help you implement views using JSP, the Spring Framework
7 min read
Spring - MVC Form Radio Button
Here, we will learn about the Spring MVC radiobutton and radiobuttons tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create radiobuttons using form:radiobutton and form:radiobuttons tags. 'spring-form.tld' tag libraryIn Spring Framework, we can use Java Server Pages (JSPs) as a view component. From version 2.0, Spr
8 min read
Spring - MVC Form Checkbox
In this article, we will learn about the Spring MVC Checkbox and Checkboxes tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create checkboxes using form:checkbox and form:checkboxes tags. 'spring-form.tld' tag library In Spring Framework, we can use Java Server Pages (JSPs) as a view component. To implement views us
6 min read
Spring - MVC Form Handling
Prerequisites: Spring MVC, Introduction to Spring Spring MVC is a Model-View-Controller framework, it enables the separation of modules into Model, View, and Controller and uniformly handles the application integration. In this article, we will create a student login form and see how Spring MVC handles form-based web-based applications. Steps to Cr
6 min read
Spring - MVC 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
14 min read
Spring - MVC Password
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this example, we will learn about the Spring MVC Passw
8 min read
Spring - MVC Form Text Field
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this example, we will learn about the Spring MVC form
8 min read
Spring - MVC Hidden Field
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this example, we will learn about the Spring MVC form
6 min read
Spring MVC - Number Validation
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
9 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
Spring - MVC RequestParam Annotation
@RequestParam annotation enables spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Here, we will see how we can use @RequestParam when building RESTful APIs for a web-based application. Context of the Application: Let us suppose we are implementing a sample feature for the 'Geeksforgeeks' web appli
5 min read
three90RightbarBannerImg