Spring MVC Architecture
Learn about the Spring MVC architecture and how it differs from the Servlets and JSP model.
Spring MVC is a web framework built on top of the Spring Framework, providing a robust architecture for developing web applications. It follows the Model-View-Controller (MVC) architectural pattern, which separates an application into three interconnected components: Model, View, and Controller. Spring MVC uses the features of the core Spring framework like Inversion of Control (IoC) and dependency injection.
Components of Spring MVC
DispatcherServlet: Acts as the front controller for Spring MVC applications. It receives incoming requests and dispatches them to the appropriate controllers for processing.
Controller: Represents the C (Controller) in the MVC pattern. Controllers handle user requests, process input, and interact with the model to prepare data for the view.
Handler mapping: Maps incoming requests to appropriate controller methods based on configured URL patterns.
View resolver: Resolves logical view names returned by controllers to actual view implementations (e.g., JSP, Thymeleaf templates).
Model: Represents the M (Model) in the MVC pattern. It encapsulates the application's business logic and data. Controllers use models to pass data to views for rendering.
Spring MVC request flow
When a request is made to a Spring MVC application, it first goes through the DispatcherServlet. The DispatcherServlet consults the Handler Mapping to determine the appropriate controller for the request. The selected controller processes the request. It creates a model and based on the user request, populates the model. Then it returns the model to the front controller. Now, the front controller passes this model to the view template which returns a logical view name. The DispatcherServlet then uses the View Resolver to find the corresponding view and renders the response. Finally, the response is sent back to the client.
Front controller
MVC architecture has a front controller that manages all the other controllers. The developer creates the controllers for the application and Spring MVC provides the front controller. The job of the front controller is to handle all requests coming from the client. It is the job of the front controller to call another controller based on the request that it receives.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.