Spring MVC Crash Course – Learn DispatcherServlet, View Resolver, JSP Integration & Form Handling

Spring MVC (Model-View-Controller) continues to hold a pivotal role in Java web development in 2025. Its clear separation of concerns, ease of integration with other tools within the Spring ecosystem, and robust handling of form inputs make it the framework of choice for creating scalable web applications. If you want to level up your Spring skills and understand how to build end-to-end web applications with Spring MVC, this guide breaks it all down step by step.

This crash course will take you through the core concepts, practical implementations, and deployment of Spring MVC applications.

Table of Contents

  1. What is Spring MVC and Why Use It in 2025?
  2. DispatcherServlet and Request Flow
  3. Setting Up Spring MVC Project
  4. Creating Your First Controller
  5. Working with JSP and View Resolvers
  6. Handling Form Data
  7. Form Validation with Hibernate Validator
  8. Exception Handling in Spring MVC
  9. Session Management and Flash Attributes
  10. Deploying Your Spring MVC App

1. What is Spring MVC and Why Use It in 2025?

Spring MVC is a powerful web framework that follows the Model-View-Controller architecture. It organizes your web applications into three distinct components, making your code modular, testable, and maintainable.

Spring MVC Architecture Overview

  • Model: Encapsulates the application’s data and business logic.
  • View: Responsible for rendering user interface elements (commonly HTML).
  • Controller: Handles user requests and manages the flow of data between the Model and the View.

MVC vs WebFlux

While Spring WebFlux is gaining traction for non-blocking, reactive programming, Spring MVC is still the go-to framework for traditional, synchronous web applications where simplicity, stability, and established patterns are critical.

When to Use Spring MVC:

  • Building form-driven web applications.
  • Applications that don’t require non-blocking APIs.
  • Existing systems that rely on servlet-style architectures.

2. DispatcherServlet and Request Flow

The DispatcherServlet acts as the front controller in Spring MVC, managing the end-to-end flow of web requests.

How DispatcherServlet Works

  • Intercept Request: It intercepts HTTP requests sent to the server.
  • Delegate Tasks: It delegates tasks to other components like controllers and view resolvers.
  • Send Response: It identifies the appropriate view and sends a response back to the client.

Request Life Cycle

  1. Client Request: Browser sends an HTTP request.
  2. DispatcherServlet: Routes the request to the appropriate handler (Controller).
  3. Handler Mapping: Maps the request URL to the corresponding Controller method.
  4. Business Logic Execution: The Controller processes the request and communicates with the Model.
  5. View Resolution: The View Resolver renders the appropriate UI.
  6. Response: The rendered view is sent back to the client.

3. Setting Up Spring MVC Project

Before writing any code, you need a proper setup.

Add Dependencies

Include the following dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <scope>provided</scope>
</dependency>

Basic Folder Structure

  • src/main/webapp/WEB-INF/views: Contains JSP files.
  • src/main/java: Contains controllers and business logic.
  • src/main/resources: Application configurations like application.properties.

4. Creating Your First Controller

Controllers handle HTTP requests and model-view interactions.

Example Controller

@Controller
@RequestMapping("/hello")
public class HelloController {

    @GetMapping
    public String showHelloPage(Model model) {
        model.addAttribute("greeting", "Hello, Spring MVC!");
        return "hello";
    }
}

When a user visits /hello, the showHelloPage method is triggered, rendering the hello.jsp view.


5. Working with JSP and View Resolvers

Integrating JSP

We use the InternalResourceViewResolver to map logical view names to actual JSP files.

Configuration in application.properties:

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

Folder Structure for Views

Place all JSP files in /WEB-INF/views/ to prevent direct access. For example, hello.jsp would reside at /WEB-INF/views/hello.jsp.


6. Handling Form Data

Spring MVC simplifies handling form data using annotations like @ModelAttribute and @RequestParam.

Example Form Handling

HTML Form in JSP (form.jsp):

<form method="POST" action="/submitForm">
    Name: <input type="text" name="name" />
    <button type="submit">Submit</button>
</form>

Controller to Process Form Data:

@PostMapping("/submitForm")
public String handleForm(@RequestParam String name, Model model) {
    model.addAttribute("message", "Hello, " + name);
    return "result";
}

Here, the controller extracts the name parameter from the form and displays it in the result.jsp view.


7. Form Validation with Hibernate Validator

Adding Validation Rules

Use annotations like @NotNull or @Size in your Model classes:

public class User {
    @NotNull
    @Size(min = 2, max = 30)
    private String name;

    // Getters and Setters
}

Validating the Input

@PostMapping("/register")
public String registerUser(@Valid @ModelAttribute User user, BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "form";
    }
    model.addAttribute("message", "Registration successful!");
    return "success";
}

Invalid fields will be highlighted in the JSP.


8. Exception Handling in Spring MVC

Using @ExceptionHandler or @ControllerAdvice, you can centralize error handling.

Example

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleExceptions(Exception e, Model model) {
        model.addAttribute("error", "An unexpected error occurred.");
        return "error";
    }
}

9. Session Management and Flash Attributes

Using HttpSession

session.setAttribute("user", new User(...));

Redirect Attributes

Flash attributes pass temporary values across redirects:

@PostMapping("/submit")
public String submit(RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute("message", "Submission successful!");
    return "redirect:/result";
}

10. Deploying Your Spring MVC App

Packaging as WAR for traditional deployment

Add these to pom.xml:

<packaging>war</packaging>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

You can then deploy the WAR file to any servlet container like Apache Tomcat.


FAQs About Spring MVC

1. Can I use Spring MVC with REST APIs?

Yes, but use @RestController for REST endpoints instead of @Controller.

2. Is JSP still relevant in 2025?

JSP is still viable for legacy systems or simpler projects, but newer view technologies like React or Thymeleaf are often preferred.

Mastering these concepts will give you the foundation needed to build scalable and robust web applications with Spring MVC. Happy coding!

Similar Posts