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:
DispatcherServlet: Acts as the front controller to handle all incoming requests.
HandlerMapping: Maps requests to the appropriate controllers.
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>
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.