Spring MVC

rajeev nayanrajeev nayan
12 min read

Table of contents

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:

  1. User sends a request (e.g., submits a form)

  2. Controller receives the request and processes it

  3. It interacts with the Model to get or update data

  4. Chooses a View to display the result

  5. 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):

  1. Separation of Concerns

    • Keeps code organized by separating data (Model), UI (View), and logic (Controller).
  2. Easier to Manage & Maintain

    • Each part can be worked on independently without affecting others.
  3. Reusability

    • Models and Views can be reused in different parts of the application.
  4. Scalability

    • Makes it easier to add new features as the app grows.
  5. Improved Testing

    • You can test components (like logic in Model or Controller) separately.
  6. 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)

  1. Based on MVC Pattern

    • Separates application into Model, View, and Controller for better structure.
  2. DispatcherServlet

    • Central controller that handles all incoming web requests.
  3. Annotation-Based Configuration

    • Uses annotations like @Controller, @RequestMapping for easy setup and cleaner code.
  4. Flexible View Resolution

    • Supports multiple view technologies like JSP, Thymeleaf, PDF, Excel, etc.
  5. Form Handling & Data Binding

    • Easily maps form inputs to Java objects and vice versa.
  6. Validation Support

    • Built-in support for validating user input using annotations like @Valid.
  7. Integration with Other Spring Modules

    • Works smoothly with Spring Boot, Spring Security, Spring Data, etc.
  8. Exception Handling

    • Simple and centralized exception handling using @ExceptionHandler.
  9. REST Support

    • Easily build RESTful web services using @RestController.
  10. 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 / FrameworkSpring MVC (Java)Django (Python)ASP.NET MVC (C#/.NET)Ruby on Rails (Ruby)
LanguageJavaPythonC#Ruby
SetupMore configuration (less with Spring Boot)Quick and easyModerateEasy (with conventions)
FlexibilityHighly flexible, customizableConvention over configurationFlexibleConvention-based, less flexible
Community SupportVery large, enterprise-levelLarge and activeStrong enterprise supportGood but smaller
Learning CurveMedium to high (Java knowledge needed)Easy to moderateModerateEasy to moderate
Speed of DevelopmentSlower (more code)FastModerateVery fast
Built-in FeaturesCore features + needs external setupComes with admin, ORM, etc.Many built-in toolsIncludes ORM, testing, etc.
REST SupportExcellent with annotationsVery good (Django REST Framework)Native supportGood

โœ… 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:

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

HomeController.java

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 @SpringBootApplication).

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:


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/ToolPurpose
JDKJava programming
IDECode writing and running
Maven/GradleDependency management & build
Spring WebCore Spring MVC functionality
Thymeleaf (or JSP)View/template rendering
DevToolsLive reload during development
Data JPA + DB driverDatabase 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:


  • 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) or src/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:

ApproachDescriptionComplexity
Spring BootAuto config, faster setupEasy
Manual configXML or Java config, more controlMore 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.

ApplicationContext

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:

TermRole
ApplicationContextSpring container that creates and manages beans and their relationships

0
Subscribe to my newsletter

Read articles from rajeev nayan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

rajeev nayan
rajeev nayan