Spring MVC

Table of contents
- Introduction to Spring MVC
- Understanding MVC Architecture
- Understanding MVC Architecture (Model-View-Controller)
- ๐งฉ 1. Model
- ๐ผ๏ธ 2. View
- ๐ฎ 3. Controller
- ๐ Flow in MVC:
- โ Benefits:
- Definition of MVC
- Components of MVC
- ๐งฉ 1. Model
- ๐ผ๏ธ 2. View
- ๐ฎ 3. Controller
- โ In short:
- Benefits of MVC architecture
- โ Benefits of MVC Architecture (Simple & Short):
- Spring MVC - An Overview
- Setting Up a Spring MVC Project
- ๐ ๏ธ Setting Up a Spring MVC Project (Step-by-Step & Simple)
- โ 1. Use Spring Initializr
- โ 2. Project Structure Overview
- โ 3. Create a Simple Controller
- โ 4. Create a View
- โ 5. Run the Application
- ๐ Done!
- Project Structure
- ๐ Spring MVC Project Structure (with Spring Boot)
- ๐ Folders Explained:
- Required Dependencies and Tools
- ๐ ๏ธ Required Dependencies and Tools for Spring MVC Project
- 1. Tools
- 2. Required Dependencies
- 3. Sample Maven Dependencies (pom.xml)
- Summary:
- Configuring a Spring MVC project
- โ๏ธ Configuring a Spring MVC Project (Simple Guide)
- 1. Using Spring Boot (Recommended & Easy)
- 2. Manual Configuration (Without Spring Boot)

Introduction to Spring MVC
Spring MVC (Model-View-Controller) is a part of the Spring Framework used to build web applications. It follows the MVC design pattern, which separates the application into:
Model โ handles data and business logic
View โ displays the data (usually HTML pages)
Controller โ processes user input and updates the Model and View
Spring MVC makes web development easier by managing these components efficiently and allowing you to build clean, maintainable, and testable application
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/home")
public class HomeController {
@GetMapping
public String displayHomepage(Model model) {
model.addAttribute("message", "Welcome to Spring MVC!");
return "home";
}
}
Overview of Spring Framework
Importance of Spring MVC in web application development
Spring Framework is a powerful, lightweight framework for building Java applications. It helps developers create flexible, scalable, and testable applications by providing tools and features like:
Dependency Injection (DI) โ to manage object creation and wiring
Aspect-Oriented Programming (AOP) โ to separate cross-cutting concerns (like logging, security)
Spring MVC โ for building web applications
Spring Boot โ for quickly building stand-alone apps with minimal setup
Data Access โ simplifies working with databases using JDBC, JPA, etc.
Spring makes Java development faster and more organized by handling many common tasks behind the scenes.
Understanding MVC Architecture
Understanding MVC Architecture (Model-View-Controller)
MVC is a design pattern used to separate an application into three main parts:
๐งฉ 1. Model
Represents the data and business logic
Directly manages data, logic, and rules of the application
Example: A
User
class that interacts with a database
๐ผ๏ธ 2. View
Represents the UI (User Interface)
Displays data from the Model to the user
Example: An HTML page showing a userโs profile
๐ฎ 3. Controller
Acts as a bridge between View and Model
Handles user input, updates the Model, and chooses the View to display
Example: A controller method that processes a login form
๐ Flow in MVC:
User sends a request (e.g., submits a form)
Controller receives the request and processes it
It interacts with the Model to get or update data
Chooses a View to display the result
Response is sent back to the user
โ Benefits:
Separation of concerns (clean code)
Easier to manage and test
Flexible and scalable design
This pattern is widely used in frameworks like Spring MVC.
Definition of MVC
MVC (Model-View-Controller) is a software design pattern that separates an application into three interconnected components:
Model โ Manages the data and business logic
View โ Handles the display and user interface
Controller โ Processes user input and updates the Model and View accordingly
Definition:
MVC is a design pattern that organizes code into three componentsโModel, View, and Controllerโto separate concerns, improve code structure, and make applications easier to develop, test, and maintain.
Components of MVC
Hereโs a simple explanation of the three main components of MVC:
๐งฉ 1. Model
Think of this as the brain of your app.
It handles data, business rules, and logic.
Example: A class that gets user info from a database.
๐ผ๏ธ 2. View
This is what the user sees โ the UI.
It displays data from the Model in a nice way.
Example: A web page showing a user's profile.
๐ฎ 3. Controller
Acts like a traffic cop โ handles what happens when a user interacts with the app.
It takes user input, tells the Model what to do, and picks the right View to show.
Example: A button click that loads new data.
โ In short:
Model = Data and logic
View = User interface
Controller = Handles input and updates the other two
This structure keeps everything organized and easier to manage.
Benefits of MVC architecture
โ Benefits of MVC Architecture (Simple & Short):
Separation of Concerns
- Keeps code organized by separating data (Model), UI (View), and logic (Controller).
Easier to Manage & Maintain
- Each part can be worked on independently without affecting others.
Reusability
- Models and Views can be reused in different parts of the application.
Scalability
- Makes it easier to add new features as the app grows.
Improved Testing
- You can test components (like logic in Model or Controller) separately.
Faster Development
- Teams can work in parallel: one on UI, another on logic, another on data.
๐ก In short: MVC makes apps more organized, flexible, and easier to build and update.
Spring MVC - An Overview
Key Features of Spring MVC
๐ Key Features of Spring MVC (Simple & Easy)
Based on MVC Pattern
- Separates application into Model, View, and Controller for better structure.
DispatcherServlet
- Central controller that handles all incoming web requests.
Annotation-Based Configuration
- Uses annotations like
@Controller
,@RequestMapping
for easy setup and cleaner code.
- Uses annotations like
Flexible View Resolution
- Supports multiple view technologies like JSP, Thymeleaf, PDF, Excel, etc.
Form Handling & Data Binding
- Easily maps form inputs to Java objects and vice versa.
Validation Support
- Built-in support for validating user input using annotations like
@Valid
.
- Built-in support for validating user input using annotations like
Integration with Other Spring Modules
- Works smoothly with Spring Boot, Spring Security, Spring Data, etc.
Exception Handling
- Simple and centralized exception handling using
@ExceptionHandler
.
- Simple and centralized exception handling using
REST Support
- Easily build RESTful web services using
@RestController
.
- Easily build RESTful web services using
Loose Coupling & Testability
- Encourages loosely coupled code, making it easier to test and maintain.
โ In short: Spring MVC is powerful, flexible, and makes building web applications in Java easier and more organized.
Comparison with other MVC frameworks
Hereโs a simple comparison of Spring MVC with other popular MVC frameworks:
Feature / Framework | Spring MVC (Java) | Django (Python) | ASP.NET MVC (C#/.NET) | Ruby on Rails (Ruby) |
Language | Java | Python | C# | Ruby |
Setup | More configuration (less with Spring Boot) | Quick and easy | Moderate | Easy (with conventions) |
Flexibility | Highly flexible, customizable | Convention over configuration | Flexible | Convention-based, less flexible |
Community Support | Very large, enterprise-level | Large and active | Strong enterprise support | Good but smaller |
Learning Curve | Medium to high (Java knowledge needed) | Easy to moderate | Moderate | Easy to moderate |
Speed of Development | Slower (more code) | Fast | Moderate | Very fast |
Built-in Features | Core features + needs external setup | Comes with admin, ORM, etc. | Many built-in tools | Includes ORM, testing, etc. |
REST Support | Excellent with annotations | Very good (Django REST Framework) | Native support | Good |
โ Summary:
Spring MVC: Great for enterprise-level Java apps, powerful and flexible.
Django: Ideal for fast web development in Python with many built-in tools.
ASP.NET MVC: Best suited for .NET/C# developers, strong for Windows-based apps.
Ruby on Rails: Great for rapid development with convention-over-configuration.
Setting Up a Spring MVC Project
๐ ๏ธ Setting Up a Spring MVC Project (Step-by-Step & Simple)
You can set up a Spring MVC project using Spring Boot (recommended) or manually with Spring Framework. Below is the Spring Boot approach, which is faster and beginner-friendly.
โ 1. Use Spring Initializr
Go to ๐ https://start.spring.io
Fill in the details:
Project: Maven (or Gradle)
Language: Java
Spring Boot version: Choose latest stable
Project Metadata:
Group:
com.example
Artifact:
springmvc-demo
Add Dependencies:
Spring Web
(Optional) Thymeleaf or Spring Boot DevTools
Click Generate to download the project ZIP โ Extract and open it in your IDE (like IntelliJ or Eclipse).
โ 2. Project Structure Overview
springmvc-demo/
โโโ src/main/java/com/example/
โ โโโ controller/
โ โโโ HomeController.java
โโโ src/main/resources/
โ โโโ templates/ โ For HTML files (if using Thymeleaf)
โ โโโ application.properties
โโโ pom.xml (for Maven)
โ 3. Create a Simple Controller
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "index"; // returns index.html from templates folder
}
}
โ 4. Create a View
src/main/resources/templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Spring MVC</title>
</head>
<body>
<h1>Welcome to Spring MVC!</h1>
</body>
</html>
โ 5. Run the Application
In your IDE, run the SpringmvcDemoApplication.java
file (with @SpringBootApplicat
ion
).
Visit: http://localhost:8080
You should see โWelcome to Spring MVC!โ
๐ Done!
Project Structure
๐ Spring MVC Project Structure (with Spring Boot)
Hereโs a typical and clean Spring MVC project structure to help you understand how everything is organized:
springmvc-demo/
โ
โโโ src/
โ โโโ main/
โ โโโ java/
โ โ โโโ com/example/springmvc/
โ โ โโโ SpringmvcDemoApplication.java โ Main app class
โ โ โโโ controller/
โ โ โ โโโ HomeController.java โ Handles web requests
โ โ โโโ model/
โ โ โ โโโ User.java โ Business/data objects
โ โ โโโ service/
โ โ โโโ UserService.java โ Business logic
โ โ
โ โโโ resources/
โ โ โโโ static/ โ For CSS, JS, images
โ โ โโโ templates/ โ For HTML or Thymeleaf views
โ โ โ โโโ index.html
โ โ โโโ application.properties โ App config
โ
โโโ pom.xml โ Maven dependencies
โโโ README.md โ Optional project notes
๐ Folders Explained:
controller/ โ Handles user input and web requests (
@Controller
classes).model/ โ Contains data objects (like
User
,Product
, etc.).service/ โ Business logic, separate from the controller.
templates/ โ HTML pages (if using Thymeleaf or JSP).
static/ โ Front-end assets like CSS, JS, and images.
application.properties โ Configuration (like port, database URL, etc.).
This structure makes the code organized, easy to maintain, and ready for scaling up as your application grows.
Required Dependencies and Tools
๐ ๏ธ Required Dependencies and Tools for Spring MVC Project
1. Tools
Java Development Kit (JDK)
- Version 8 or higher (Java 11+ recommended)
IDE (Integrated Development Environment)
- IntelliJ IDEA, Eclipse, or VS Code with Java support
Build Tool
- Maven (commonly used) or Gradle
Web Browser
- To test your application (Chrome, Firefox, etc.)
2. Required Dependencies
If you use Spring Initializr (https://start.spring.io), add these:
Spring Web
- Core dependency for building web apps with Spring MVC
-
- For server-side HTML templates (you can also use JSP or others)
Spring Boot DevTools (optional)
- Enables hot reload during development
Spring Data JPA (optional)
3. Sample Maven Dependencies (pom.xml)
<dependencies>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf template engine -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Boot DevTools for auto reload -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- For database (optional) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Database driver example (H2 in-memory) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Summary:
Dependency/Tool | Purpose |
JDK | Java programming |
IDE | Code writing and running |
Maven/Gradle | Dependency management & build |
Spring Web | Core Spring MVC functionality |
Thymeleaf (or JSP) | View/template rendering |
DevTools | Live reload during development |
Data JPA + DB driver | Database access (optional) |
Configuring a Spring MVC project
โ๏ธ Configuring a Spring MVC Project (Simple Guide)
You can configure Spring MVC either manually (XML/Java config) or using Spring Boot (auto-configuration). Spring Boot makes it much easier, so hereโs both ways briefly:
1. Using Spring Boot (Recommended & Easy)
Spring Boot auto-configures most things for you.
Just add the dependency
spring-boot-starter-web
.Create your main application class with
@SpringBootApplication
.Use
@Controller
and@RequestMapping
in your controllers.Place your views in
src/main/resources/templates
(for Thymeleaf) orsrc/main/webapp/WEB-INF/views
(for JSP).
Example Main Class:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
application.properties (optional):
server.port=8080
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
2. Manual Configuration (Without Spring Boot)
a) web.xml
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
b) dispatcher-servlet.xml
<context:component-scan base-package="com.example.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
c) Controller
@Controller
public class HomeController {
@RequestMapping("/")
public String home() {
return "index"; // Maps to /WEB-INF/views/index.jsp
}
}
Summary:
Approach | Description | Complexity |
Spring Boot | Auto config, faster setup | Easy |
Manual config | XML or Java config, more control | More complex |
DispatcherServlet
DispatcherServlet is the core component of Spring MVC. Think of it as the front controller โ the main entry point for all HTTP requests in a Spring MVC application.
Itโs like the traffic police of your web app.
itโs role:
Catches every request that comes to your app
Finds the right controller to handle the request
Tells the controller to do its job (like getting data)
Chooses which page (view) to show back to the user
Sends the response back to the userโs browser
In short:
Without DispatcherServlet, your app wouldnโt know how to handle requests or where to send them. Itโs the main coordinator that makes sure everything runs smoothly.
What is ApplicationContext in Spring? (Easy Explanation)
ApplicationContext is like the heart of the Spring Framework โ itโs a container that:
Manages all the beans (objects) in your application
Creates, configures, and wires those beans together (using Dependency Injection)
Provides many services like resource loading, event propagation, and more
Why do we need ApplicationContext?
Instead of manually creating and connecting objects in your code, ApplicationContext does it automatically for you โ making your app cleaner and easier to manage.
Role of ApplicationContext:
Loads bean definitions from configuration (XML, annotations, or Java code)
Creates and manages the lifecycle of beans
Allows beans to find and use other beans
Provides support for internationalization, events, and more
Simple analogy:
Think of ApplicationContext as a factory manager that knows about all the parts (beans), how to build them, and how they fit together.
Summary:
Term | Role |
ApplicationContext | Spring container that creates and manages beans and their relationships |
Subscribe to my newsletter
Read articles from rajeev nayan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
