In Spring MVC, the Controller, Model, and View form the core components that make up the MVC architecture. These elements work together to create dynamic, user-friendly web applications.
Controllers
Controllers in Spring MVC handle incoming HTTP requests and return the appropriate response. They act as the middle layer between the user and the application’s business logic. In Spring MVC, a controller is simply a Java class annotated with @Controller
. The methods within the controller are mapped to specific URL patterns using @RequestMapping
.
For example:
1 2 3 4 5 6 7 8 9 |
@Controller public class MyController { @RequestMapping("/hello") public String greet(Model model) { model.addAttribute("message", "Hello, Spring MVC!"); return "greet"; } } |
In the above example, when the user visits the /hello
URL, the greet()
method is invoked, and the response is forwarded to a view named “greet.”
Models
The Model represents the data and the state of the application. It holds the attributes or properties that the controller sends to the view. In Spring MVC, data is passed from the controller to the view via the Model
object, which can be populated with attributes using the addAttribute()
method.
For example:
1 |
model.addAttribute("user", new User("John", 30)); |
Here, the controller is adding a User
object to the model. This data will be available to the view for rendering.
Views
The View is responsible for rendering the output (the response) to the client. In Spring MVC, views are typically JSP files, Thymeleaf templates, or other technologies that render HTML content. The view is resolved by the ViewResolver
in Spring, based on the logical view name returned by the controller.
For example, in the previous controller code, the string "greet"
is returned, which corresponds to a view (usually a JSP file or a Thymeleaf template) that will render the data.
Working of MVC
- User Request: The user sends an HTTP request to the application.
- Controller: The controller receives the request, processes any necessary business logic, and adds attributes to the model.
- Model: The model carries the data to the view.
- View: The view uses the model’s data to generate a response (e.g., an HTML page) that is sent back to the user.