Spring MVC (Model-View-Controller)

Spring MVC is a popular web framework that follows the Model-View-Controller (MVC) design pattern. It is used to build scalable, maintainable, and testable web application

Introduction to the Spring MVC Architecture

The Spring MVC framework divides the application into three interconnected components:

  • Model: Represents application data and business logic.
  • View: Displays data to the user, typically using JSP or other templating technologies.
  • Controller: Handles HTTP requests, processes data, and maps it to the appropriate view.

Key Components:

  1. DispatcherServlet: Acts as the front controller to handle all incoming requests.
  2. HandlerMapping: Maps requests to the appropriate controllers.
  3. ViewResolver: Resolves logical view names into actual view pages.

Setting Up a Spring MVC Application with XML Configuration

a. Maven Dependencies

Add the following dependencies to your pom.xml:

<dependencies>
    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.9</version>
    </dependency>
    <!-- JSP support -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
</dependencies>

b. Directory Structure

Your project should have the following structure:

src/main/java
    ├── com.example.controller
        └── HomeController.java
src/main/webapp
    ├── WEB-INF
        ├── web.xml
        ├── spring-servlet.xml
        └── views
            └── home.jsp

c. Configure web.xml

web.xml defines the DispatcherServlet, which acts as the entry point for the application.

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.1">
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

d. Configure Spring (spring-servlet.xml)

The spring-servlet.xml file contains the core Spring MVC configuration.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- Enable component scanning -->
    <context:component-scan base-package="com.example.controller" xmlns:context="http://www.springframework.org/schema/context"/>
    
    <!-- Configure View Resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

Writing Controllers and Handling HTTP Requests

Create a controller class to handle incoming HTTP requests and return appropriate views.

HomeController.java

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"; // Logical view name (resolved to /WEB-INF/views/home.jsp)
    }
}

Configuring JSP View Resolvers

The InternalResourceViewResolver maps logical view names returned by the controller to JSP files in the WEB-INF/views directory.

home.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

Running the Application

  • Deploy on a Tomcat Server:

    • Place the WAR file in Tomcat’s webapps directory.
    • Start the server and navigate to http://localhost:8080/{project-name}/.
  • Expected Output:
    A page with the message: “Welcome to Spring MVC!”

Best Practices for Spring MVC

  • Use Annotations:
    Prefer annotations (@Controller, @RequestMapping, @GetMapping) over XML for cleaner and less verbose configurations.

  • Organize Code:

    • Separate controllers, services, and DAOs into different packages.
    • Keep your WEB-INF/views folder organized with subfolders for modularity.
  • Error Handling:
    Use @ControllerAdvice to handle exceptions globally.

  • Security:
    Integrate Spring Security for secure web applications.

  • Validation:
    Use @Valid and the BindingResult interface for input validation.