Popular Searches
Popular Course Categories
Popular Courses

Introduction to Spring MVC Architecture

Introduction to Spring MVC Architecture

Spring MVC and Enterprise Web Development

Introduction to Spring MVC Architecture

Course: Advanced Java Training

Topic: Introduction to Spring MVC Architecture

Course Link: Advanced Java Training

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Spring MVC

Spring MVC is a web framework provided by the Spring Framework for developing Java-based web applications. MVC stands for Model-View-Controller, a design pattern that separates application data, presentation, and request-handling responsibilities.

Spring MVC provides a structured approach to processing HTTP requests, executing application logic, managing model data, rendering views, validating user input, and handling exceptions.

It is commonly used to build web applications such as student management systems, e-commerce websites, employee portals, banking applications, and enterprise management systems.

Objectives of Spring MVC

  • Understand the Model-View-Controller design pattern.
  • Learn the responsibilities of the DispatcherServlet.
  • Understand how incoming HTTP requests are processed.
  • Learn about controllers, handler mappings, and handler adapters.
  • Understand how models transfer data to views.
  • Learn how ViewResolver identifies the appropriate view.
  • Build maintainable Java web applications.

2. What Is the MVC Design Pattern?

MVC is an architectural pattern that divides an application into three main components: Model, View, and Controller. Each component performs a distinct responsibility, making the application easier to maintain and extend.

2.1 Model

The Model represents application data and information used by the business layer. It may contain Java objects, domain entities, form objects, and data retrieved from a database.

Responsibilities:

  • Represent application data.
  • Carry information between application layers.
  • Provide data required by the presentation layer.
  • Support the application's data-processing workflow.

Example:

public class Student {
    private int id;
    private String name;
    private String email;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

The Student class represents information about a student. A controller can create or retrieve a Student object and make it available to a view.

2.2 View

The View is responsible for presenting information to the user. Traditional Spring MVC applications commonly use JSP, Thymeleaf, or other supported template technologies.

Responsibilities:

  • Display application information.
  • Render HTML pages.
  • Present messages and results.
  • Display model attributes.
  • Provide forms for user input.

Example using JSP:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Student Details</title>
</head>
<body>
    <h2>Student Information</h2>
    <p>Name: ${student.name}</p>
    <p>Email: ${student.email}</p>
</body>
</html>

The JSP page displays the student's name and email using the model attribute named student.

2.3 Controller

The Controller receives web requests, coordinates application processing, and determines what result should be returned. Spring MVC controller classes are commonly annotated with @Controller.

Responsibilities:

  • Handle incoming HTTP requests.
  • Map URLs to handler methods.
  • Read request parameters and form data.
  • Call service-layer methods.
  • Add data to the model.
  • Return a view name or an HTTP response.

Example:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class StudentController {

    @GetMapping("/student")
    public String showStudent(Model model) {
        Student student = new Student();
        student.setId(1);
        student.setName("Rahul");
        student.setEmail("[email protected]");

        model.addAttribute("student", student);

        return "student";
    }
}

When a user visits /student, the controller creates a Student object, adds it to the model, and returns the logical view name student.

3. What Is Spring MVC Architecture?

Spring MVC architecture defines how web components collaborate to process an HTTP request and produce an appropriate response. Its central component is the DispatcherServlet, which implements the Front Controller design pattern.

The DispatcherServlet receives requests and coordinates handler selection, controller invocation, exception handling, model preparation, view resolution, and response rendering.

Major Components of Spring MVC

Component Purpose
Client Sends HTTP requests using a browser or another HTTP client.
DispatcherServlet Central entry point that coordinates request processing.
HandlerMapping Identifies the appropriate handler for a request.
HandlerAdapter Invokes the selected handler using the appropriate mechanism.
Controller Handles the request and coordinates application logic.
Service Layer Executes business rules and application operations.
Repository or DAO Manages data-access operations when a persistence layer is used.
Model Carries data needed by the view.
ViewResolver Resolves a logical view name to a configured view.
View Renders the final presentation, such as an HTML page.

4. Spring MVC Architecture Diagram

             +----------------------+
             |   Client / Browser   |
             +----------+-----------+
                        |
                        | HTTP Request
                        v
             +----------------------+
             |   DispatcherServlet  |
             +----------+-----------+
                        |
                        v
             +----------------------+
             |    HandlerMapping    |
             +----------+-----------+
                        |
                        v
             +----------------------+
             |    HandlerAdapter    |
             +----------+-----------+
                        |
                        v
             +----------------------+
             |      Controller      |
             +----------+-----------+
                        |
                        v
             +----------------------+
             |     Service Layer    |
             +----------+-----------+
                        |
                        v
             +----------------------+
             | Repository / Database|
             +----------+-----------+
                        |
                        | Data returned
                        v
             +----------------------+
             | Controller and Model |
             +----------+-----------+
                        |
                        v
             +----------------------+
             |     ViewResolver     |
             +----------+-----------+
                        |
                        v
             +----------------------+
             |     View Template    |
             +----------+-----------+
                        |
                        | HTTP Response
                        v
             +----------------------+
             |   Client / Browser   |
             +----------------------+

Important: This diagram illustrates a typical server-rendered Spring MVC application. In a REST API built with @RestController, methods generally return response bodies directly, so a server-side ViewResolver is not normally required.

5. Understanding DispatcherServlet

DispatcherServlet is the central component of Spring MVC. It acts as a front controller, providing a common entry point for incoming requests and coordinating their processing.

Responsibilities of DispatcherServlet

  • Receive HTTP requests.
  • Consult HandlerMapping to identify the appropriate handler.
  • Use a HandlerAdapter to invoke the handler.
  • Process the result returned by the handler.
  • Coordinate exception resolution when errors occur.
  • Resolve and render views for view-based responses.
  • Return the resulting HTTP response to the client.

Centralized request processing reduces the need to implement the same request-handling infrastructure separately for every controller.

6. Understanding HandlerMapping

HandlerMapping determines which controller or handler method should process a request. It evaluates mapping conditions such as the URL path, HTTP method, and other request attributes.

Spring MVC supports annotations such as @RequestMapping, @GetMapping, and @PostMapping for declaring request mappings.

Example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class ProductController {

    @GetMapping("/products")
    public String showProducts() {
        return "products";
    }

    @PostMapping("/products")
    public String saveProduct() {
        return "product-success";
    }
}

A GET request to /products invokes showProducts(), while a POST request to the same path invokes saveProduct().

7. Understanding HandlerAdapter

HandlerAdapter invokes the handler selected by HandlerMapping. It allows DispatcherServlet to work with different types of handlers without directly managing their individual invocation mechanisms.

Key benefits:

  • Separates handler selection from handler execution.
  • Supports annotation-based controller methods.
  • Helps maintain a flexible request-processing architecture.
  • Reduces dependencies between the DispatcherServlet and individual handler implementations.

8. Role of the Controller

A controller receives a request after Spring identifies the appropriate handler. It processes request data, calls service methods when necessary, prepares model attributes, and returns a result.

Controllers should focus on web-layer responsibilities. Complex business rules and database operations should generally be delegated to service and repository layers.

Example:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @GetMapping("/greet")
    public String greet(
            @RequestParam(defaultValue = "Guest") String name,
            Model model) {

        model.addAttribute("message", "Welcome, " + name);

        return "greeting";
    }
}

Opening /greet?name=Anita supplies the value Anita to the controller. The controller adds a greeting to the model and returns the greeting view.

9. Understanding Model and ModelAndView

The Model interface allows controllers to add attributes that can be accessed by a view. A controller commonly returns a logical view name as a String while passing the required data through the Model.

Using Model

@GetMapping("/welcome")
public String welcome(Model model) {
    model.addAttribute("username", "Anita");
    return "welcome";
}

Using ModelAndView

import org.springframework.web.servlet.ModelAndView;

@GetMapping("/dashboard")
public ModelAndView dashboard() {
    ModelAndView mav = new ModelAndView("dashboard");
    mav.addObject("title", "Student Dashboard");
    return mav;
}
Model ModelAndView
Primarily carries model attributes. Combines model attributes with view information.
Often used when the controller returns a view name separately. Useful when returning model data and a view together.

10. Understanding ViewResolver

ViewResolver maps a logical view name returned by a controller to an actual view resource. Its configuration depends on the selected view technology and application setup.

For example, returning "student" may resolve to /WEB-INF/views/student.jsp in a traditional JSP-based application.

Example configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;
    }
}

With this configuration, the logical view name student resolves to /WEB-INF/views/student.jsp. This example assumes the required Spring MVC dependencies and servlet application configuration are in place.

11. Complete Request-Response Lifecycle

The following steps describe a typical request in a server-rendered Spring MVC application.

  1. Client sends a request: The browser requests a URL such as /students.
  2. DispatcherServlet receives the request: The central servlet accepts the incoming HTTP request.
  3. HandlerMapping locates the handler: Spring identifies the controller method matching the request.
  4. HandlerAdapter invokes the handler: The selected controller method is executed.
  5. Controller processes the request: The controller interprets request data and calls the service layer when required.
  6. Service performs business operations: Business rules are applied and a repository may access the database.
  7. Controller prepares the model: The required data is added to the model, and a logical view name is returned.
  8. ViewResolver resolves the view: The logical name is mapped to the configured view resource.
  9. View renders the result: The view combines template content with model attributes.
  10. Response returns to the client: The rendered response is sent to the browser.

12. Creating a Simple Spring MVC Application

Step 1: Add the Required Dependency

In a traditional Maven-based Spring MVC project, add the Spring Web MVC dependency and the servlet API appropriate for your target container. Include the required JSP or template-engine dependencies when needed.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>6.2.0</version>
</dependency>

The version is an illustrative example, not a recommendation to use that exact release in every project. Choose a supported version compatible with your Java version and deployment environment. Spring Framework 6 requires Java 17 or later and uses Jakarta EE APIs.

Step 2: Create a Controller

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute(
            "message",
            "Welcome to Spring MVC"
        );

        return "home";
    }
}

Step 3: Create a JSP View

Create a JSP file named home.jsp in the directory configured for views.

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Spring MVC Home</title>
</head>
<body>
    <h1>${message}</h1>
    <p>Your first Spring MVC page is working.</p>
</body>
</html>

Step 4: Configure the Application

Configure component scanning, Spring MVC infrastructure, and view resolution. A traditional servlet application must also register DispatcherServlet through servlet configuration or a Java-based initializer. The exact setup depends on whether the project uses traditional WAR deployment or Spring Boot.

Step 5: Run and Test

  • Deploy the application to a compatible servlet container or run it using the selected development setup.
  • Open the application's root URL in a browser.
  • Verify that the controller executes and the home page displays the expected message.
  • Check application logs if request mapping or view resolution fails.

13. Important Spring MVC Annotations

Annotation Purpose
@Controller Marks a class as a Spring MVC controller.
@RestController Combines controller functionality with response-body handling by default.
@RequestMapping Defines request mapping conditions at class or method level.
@GetMapping Maps HTTP GET requests.
@PostMapping Maps HTTP POST requests.
@PutMapping Maps HTTP PUT requests.
@DeleteMapping Maps HTTP DELETE requests.
@RequestParam Binds request parameters to method arguments.
@PathVariable Binds URI path variables to method arguments.
@ModelAttribute Binds request data to an object or exposes an object to the model.
@ResponseBody Writes a method's return value to the HTTP response body.
@ExceptionHandler Handles specified exceptions in a controller or applicable advice class.

14. Spring MVC vs. Spring Boot

Spring MVC Spring Boot
A web framework within the Spring ecosystem. Simplifies the configuration and setup of Spring applications.
May require explicit servlet and view configuration. Provides auto-configuration and starter dependencies.
Can be deployed to an external servlet container. Can run with an embedded server or be packaged for external deployment.
Can be used independently of Spring Boot. Can use Spring MVC to build web applications and REST APIs.

15. Advantages of Spring MVC Architecture

  • Separation of concerns: Divides request handling, business operations, and presentation.
  • Maintainability: Makes application components easier to update and troubleshoot.
  • Flexible presentation: Supports different server-side view technologies.
  • Annotation-based development: Simplifies controller and URL mapping definitions.
  • Spring integration: Works with dependency injection, validation, security, and persistence technologies.
  • Testability: Enables independent testing of controllers and services.
  • Centralized request processing: Uses DispatcherServlet to coordinate web requests.
  • REST support: Supports APIs through response bodies and HTTP message converters.

16. Common Errors and Troubleshooting

Problem Possible Cause Solution
404 Not Found No matching handler or incorrect application path. Check the URL, context path, controller scanning, and mappings.
View not found Incorrect view name, prefix, suffix, or file location. Verify ViewResolver configuration and view-resource placement.
405 Method Not Allowed The requested HTTP method does not match the mapping. Check GET, POST, PUT, and DELETE mappings.
400 Bad Request Invalid request data or failed parameter conversion. Check input values, argument types, and validation errors.
500 Internal Server Error Unhandled exception or server-side failure. Inspect application logs and exception traces.
Model attribute missing Attribute not added or name mismatch in the view. Verify model attribute names and template expressions.
Controller not detected Component scanning excludes the controller package. Review package structure and component-scan configuration.

17. Spring MVC Best Practices

  • Keep controller methods focused on HTTP and presentation responsibilities.
  • Place business rules in service classes.
  • Use repositories or DAOs to isolate persistence logic.
  • Validate user input before performing important operations.
  • Use consistent exception handling and appropriate HTTP status codes.
  • Avoid exposing internal exception details or sensitive data to users.
  • Use dependency injection rather than manually creating shared dependencies.
  • Prefer constructor injection for required dependencies.
  • Write unit and integration tests for controllers and services.
  • Apply appropriate authentication, authorization, CSRF protection, and session-security practices.

18. Practical Exercise

Project: Student Information Management Page

Create a small Spring MVC application that displays student information in a browser.

Requirements

  1. Create a Student model containing ID, name, email, and course fields.
  2. Create a StudentController with a GET mapping for /students.
  3. Prepare sample student data and add it to the model.
  4. Create a JSP or another supported template to display student information.
  5. Configure DispatcherServlet and ViewResolver as required.
  6. Test the application and resolve mapping or view-rendering errors.

Expected Learning Outcome

After completing this exercise, learners should understand how a request travels through DispatcherServlet and a controller to the model and view, and how the response is returned to the client.

19. Interview Questions and Answers

Q1. What is Spring MVC?

Answer: Spring MVC is a Spring web framework based on the Model-View-Controller design pattern. It supports request handling, controller development, model management, and view rendering.

Q2. What is DispatcherServlet?

Answer: DispatcherServlet is the front controller of Spring MVC. It coordinates handler mapping, handler invocation, exception resolution, and view rendering.

Q3. What is the difference between Model and View?

Answer: The Model carries data needed for presentation, while the View renders that data into a user-facing response such as an HTML page.

Q4. What is HandlerMapping?

Answer: HandlerMapping identifies the appropriate handler based on request mappings and request conditions.

Q5. What is HandlerAdapter?

Answer: HandlerAdapter invokes the selected handler using the appropriate execution mechanism.

Q6. What is ViewResolver?

Answer: ViewResolver maps a logical view name returned by a controller to the configured view resource.

Q7. What is the difference between @Controller and @RestController?

Answer: @Controller is commonly used for controllers that return view names. @RestController combines @Controller and @ResponseBody behavior, so returned values are generally written directly to the HTTP response body.

Q8. Can Spring MVC be used without Spring Boot?

Answer: Yes. Spring MVC can be configured in a traditional Spring web application without Spring Boot.

Q9. How are form submissions handled in Spring MVC?

Answer: A controller maps the submitted HTTP request, binds input to method arguments or a form object, validates the data, invokes business logic, and returns a view or redirect.

Q10. Why separate controllers, services, and repositories?

Answer: This separation improves maintainability, testability, and code reuse by keeping web handling, business rules, and data access responsibilities distinct.

20. Quick Revision Checklist

  • MVC stands for Model, View, and Controller.
  • Spring MVC is a web framework in the Spring ecosystem.
  • DispatcherServlet is the central front controller.
  • HandlerMapping identifies the appropriate handler.
  • HandlerAdapter invokes the selected handler.
  • Controllers process web requests and coordinate application logic.
  • Model carries attributes required by the view.
  • ViewResolver resolves logical view names.
  • REST controllers usually return response bodies rather than view names.
  • Service and repository layers help separate business logic from data access.

21. Conclusion

Spring MVC provides a structured approach to building Java web applications by separating request handling, business operations, data preparation, and presentation. Understanding DispatcherServlet, HandlerMapping, HandlerAdapter, Controller, Model, and ViewResolver is essential for developing and troubleshooting Spring MVC applications.

By practising request mappings, model attributes, view templates, validation, and exception handling, developers can create web applications that are easier to maintain, test, and extend.

Explore the Advanced Java Training course at JustAcademy to learn more about Java web development.

Visit the JustAcademy official website or register for a course demo to learn more about available training options.

Previous Next
whatsapp