Introduction to Spring MVC Architecture


Table of Contents

  1. Introduction
  2. What is Spring MVC?
  3. Components of Spring MVC
    • DispatcherServlet
    • HandlerMapping
    • Controller
    • ViewResolver
    • Model
  4. Spring MVC Workflow
  5. Advantages of Using Spring MVC
  6. Setting Up a Basic Spring MVC Application
  7. Conclusion

1. Introduction

Spring MVC (Model-View-Controller) is one of the core frameworks within the Spring ecosystem. It provides a powerful, flexible framework for building web applications. Spring MVC follows the popular MVC architectural pattern, which separates the application into three main components: Model, View, and Controller. This separation of concerns leads to cleaner, more maintainable, and testable code.

This module introduces you to the Spring MVC architecture, its components, workflow, and how it can be leveraged to build modern web applications.


2. What is Spring MVC?

Spring MVC is a request-driven framework used for building Java-based web applications. It is based on the servlet API and provides a simple and extensible mechanism for handling web requests, dispatching them to the appropriate controllers, and rendering views.

In Spring MVC, HTTP requests are mapped to specific controller methods, which process the requests and return a model object that is passed to the view. This architecture encourages clean separation of concerns, making the application easier to manage, extend, and test.


3. Components of Spring MVC

Spring MVC is composed of several key components that work together to handle HTTP requests and responses.

DispatcherServlet

The DispatcherServlet is the central servlet in Spring MVC. It acts as the front controller that receives all incoming HTTP requests and delegates them to appropriate handlers (controllers). The DispatcherServlet is responsible for coordinating the workflow of the Spring MVC framework.

  • Role: Acts as the controller and dispatches the request to various components.
  • Configuration: The DispatcherServlet is defined in the web.xml file or in Java-based configuration.

HandlerMapping

The HandlerMapping component is responsible for mapping incoming HTTP requests to the appropriate handler method in the controller. It uses the request URL, HTTP method, and other factors to determine which controller method should handle the request.

  • Role: Maps HTTP requests to specific handler methods (controllers).
  • Configuration: Handlers are typically mapped using annotations like @RequestMapping or @GetMapping.

Controller

A Controller in Spring MVC is a Java class that processes incoming requests, manipulates data (model), and returns a view to be rendered. Controllers contain methods annotated with request mapping annotations (@RequestMapping, @GetMapping, etc.) to map HTTP requests to corresponding methods.

  • Role: Handles user requests and returns the response data.
  • Configuration: You can define controller methods in classes annotated with @Controller.

ViewResolver

The ViewResolver is responsible for selecting and rendering the appropriate view based on the model data returned by the controller. The view could be a JSP, Thymeleaf template, or any other view technology.

  • Role: Resolves the view name returned by the controller into an actual view (e.g., JSP, HTML).
  • Configuration: Configured in Spring’s applicationContext.xml or Java-based configuration.

Model

The Model represents the data that the controller works with. The model is typically returned by the controller and passed to the view for rendering. It may consist of simple Java objects, collections, or even complex objects that need to be displayed to the user.

  • Role: Holds the data that is passed from the controller to the view.
  • Configuration: Data is usually added to the model using Model, ModelMap, or ModelAndView.

4. Spring MVC Workflow

  1. HTTP Request: When a user sends an HTTP request (for example, by clicking a link or submitting a form), the request is intercepted by the DispatcherServlet.
  2. Handler Mapping: The DispatcherServlet consults the HandlerMapping to determine which controller method should handle the request.
  3. Controller Execution: The appropriate controller method is executed. The controller processes the request, manipulates the model data, and prepares the model object.
  4. View Resolution: The controller returns the logical name of the view (e.g., “home”). The ViewResolver is used to map the logical view name to the actual view template (e.g., a JSP file).
  5. Rendering the View: The resolved view (e.g., JSP, Thymeleaf) is rendered, and the model data is used to populate the view.
  6. HTTP Response: Finally, the response is sent back to the user’s browser, and the rendered view is displayed.

5. Advantages of Using Spring MVC

  • Separation of Concerns: Spring MVC enforces the separation of concerns between the Model, View, and Controller, which leads to cleaner, more modular, and maintainable code.
  • Flexibility: It offers flexibility in terms of view technologies (JSP, Thymeleaf, etc.), controllers, and handler mappings.
  • Extensibility: Spring MVC is highly extensible, allowing developers to customize various components like HandlerMapping, Controller, ViewResolver, etc.
  • Integration: It integrates seamlessly with other Spring frameworks such as Spring Security, Spring Data, and Spring Boot.
  • Testability: Since controllers are designed as plain Java classes (POJOs), Spring MVC supports easy unit testing using tools like JUnit.

6. Setting Up a Basic Spring MVC Application

Here’s a quick guide to setting up a simple Spring MVC application:

1. Add Spring MVC Dependencies

If you’re using Maven, add the following dependencies to your pom.xml:

xmlCopyEdit<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.x.x</version>
    </dependency>
</dependencies>

2. Configure the DispatcherServlet

In web.xml (for XML-based configuration):

xmlCopyEdit<web-app>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3. Create a Simple Controller

javaCopyEdit@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "hello";  // Logical view name
    }
}

4. Create a View (JSP Example)

Create a hello.jsp file in the WEB-INF/views directory:

jspCopyEdit<html>
    <body>
        <h1>${message}</h1>
    </body>
</html>

5. Configure ViewResolver

In servlet-context.xml (Spring’s application context):

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

6. Run the Application

Now, if you run the application and visit http://localhost:8080/hello, you should see the “Hello, Spring MVC!” message rendered on the page.


7. Conclusion

Spring MVC provides a well-defined architecture for developing web applications with a clean separation between the business logic (model), presentation (view), and input processing (controller). Understanding its core components—such as DispatcherServlet, HandlerMapping, Controller, and ViewResolver—is essential for building efficient, maintainable, and scalable web applications.