MVC Introduction
Imagine a restaurant. You (the client) place an order. A waiter takes your order to the kitchen. The chef prepares the food. The waiter then brings the food back to you. You never go into the kitchen – the waiter handles everything.
Spring MVC works exactly like this restaurant. It is a web framework that follows the Model-View-Controller design pattern.
Spring MVC works exactly like this restaurant. It is a web framework that follows the Model-View-Controller design pattern.
MVC Components:
- Model – Contains the data (like food being prepared). In Spring, this is usually a POJO or a service class.
- View – What the user sees (like the food served). In Spring, this can be JSP, Thymeleaf, HTML, etc.
- Controller – Handles user requests, processes them, and returns the view (like the waiter).
Spring MVC has one special component: DispatcherServlet (the head waiter). It receives all incoming requests and decides which controller should handle them.
Here is a simple Spring MVC controller:
@Controller
public class HomeController {
@RequestMapping("/")
public String home(Model model) {
model.addAttribute("message", "Welcome to Spring MVC!");
return "home"; // This is the view name (home.jsp or home.html)
}
}
When a user visits
/, DispatcherServlet calls home() method. The method adds data to the Model and returns the view name "home". DispatcherServlet then renders the home page.Two Minute Drill
- Spring MVC implements the Model-View-Controller pattern.
- DispatcherServlet is the front controller that handles all requests.
- @Controller marks a class as a controller.
- @RequestMapping maps URLs to methods.
- Model carries data from controller to view.
Need more clarification?
Drop us an email at career@quipoinfotech.com
