SoFunction
Updated on 2025-03-10

Interpret Spring MVC's workflow

Spring MVC's workflow is a typical implementation based on the Model-View-Controller (MVC) design pattern, and the following are its main workflow steps:

Spring MVC workflow

Client request is sent to the front-end controller (DispatcherServlet)

  • The user sends a request through the browser, which first reaches the front-end controller of Spring MVCDispatcherServlet
  • This class is the core of the entire process, which is responsible for coordinating the execution of other components.

The front-end controller forwards the request to the processor mapper (Handler Mapping)

  • DispatcherServletAfter receiving the request, find the corresponding processor according to the requested URL (Controller) to process the request.
  • This map isHandler MappingComplete, it looks for the specific processor based on the configuration.

The processor mapper finds the corresponding controller (Controller)

  • Handler MappingDetermine which one to use based on the requested pathControllerto process the request.
  • After finding it, it returnsControllerInformation toDispatcherServlet

The front-end controller calls the target processor (Controller)

  • DispatcherServletaccording toHandler MappingThe information provided, call the specificControllerProcess the request.
  • The business logic in the controller processes the client's data and returns aModelAndViewObject, containing model data and view names.

The controller returns the model data and view names

  • ControllerReturn the processed model data and view names toDispatcherServlet

Front-end controller requests view resolver (View Resolver)

  • DispatcherServletLeave the view name to the view resolverView Resolver
  • It is responsible for resolving the view name into a specific view (such as JSP, Thymeleaf, etc.)

View parser generates views

  • The view parser will find the corresponding physical view file according to the configuration.
  • and return toDispatcherServlet

Front-end controller passes model data to view

  • DispatcherServletPass the model data returned by the controller to the parsed view
  • Usually these data will passModelorModelAndViewObject delivery

View rendering

  • Views are rendered in combination with model data
  • Generate the final HTML page

Front-end controller responds to client

  • The rendered view isDispatcherServletReturn to the client (browser)
  • What the end user sees is the processed page content

example

Suppose we have a simple web application that displays the user's personal information. When the user visits/user/1When this URL, the application displays user information with ID 1.

Detailed steps

The user sends a request to the server: The user enters the URL in the browser/user/1,for examplehttp://localhost:8080/user/1, this request is sent to the server.

Front-end controller (DispatcherServlet) receives requests: The core components of Spring MVCDispatcherServletWill intercept all incoming HTTP requests. It is equivalent to the entry point of the request and is responsible for distributing the request to the appropriate processor (Controller).

  • Request path in the example/user/1quiltDispatcherServletIntercept, ready to be assigned to the corresponding processor.

Find controllers through Handler MappingDispatcherServletUsing Processor Mapper (HandlerMapping) Find the right controller to handle it/user/1ask. This mapping process is usually matched based on the URL path.

  • For example,@RequestMapping("/user/{id}")The annotation can tell Spring that this method is responsible for processing/user/{id}request.
  • In our case, the processor mapper will findUserController, the controller is responsible for handling all user-related requests.

Controller handles requests: After finding the appropriate controller,DispatcherServletForward the request to the controller. The controller contains the business logic of the application, which is responsible for processing user requests and returning data.

  • In this example,UserControllerThe method will accept the user's ID (e.g.1) and get user information with ID 1 from the database or memory.
@Controller
public class UserController {
    @RequestMapping("/user/{id}")
    public ModelAndView getUser(@PathVariable("id") int userId) {
        // Simulate to obtain user data from the database        User user = (userId);
        ModelAndView mav = new ModelAndView("userView");
        ("user", user);
        return mav;
    }
}

In this example:

  • getUserThe method will be fromuserServiceGet user data and store the data inModelAndViewIn the object, return toDispatcherServlet
  • "userView"It is the name of the view. Spring MVC will find the appropriate view template based on this name (such as JSP pages, Thymeleaf pages, etc.).
  • ("user", user)Store user information in the model for use by the view.

Return the model and view to the DispatcherServlet: The controller method returns aModelAndViewObject, containing model data (user information) and view name (userView)。DispatcherServletReceive this return object.

Find views through View ResolverDispatcherServletThe view name will be added (eg"userView") handed over to the view parser (ViewResolver), it finds the physical view file according to the configuration.

View parser generates views: The view parser will findand return toDispatcherServlet. At this time, the view has not yet rendered the user data, but has just found the physical file.

Front-end controller passes model data to viewDispatcherServletPass the user data (model) returned by the controller toview. The view file uses this data to generate dynamic HTML pages.

View rendering: View () Render with model data. For example, expressions may be used in JSP files.${}to display the user's name.

Return response to client: The rendered HTML page is returned to the client (user's browser). What users end up seeing is a complete page containing user information.

Note:

  • When using Spring Boot for front-end separation transmission, the backend is only responsible for providing data interfaces (usually in the form of RESTful APIs), and the frontend is responsible for rendering pages and handling user interactions.
  • This architecture manifests itself as a RESTful API in Spring Boot, and no longer returns views like traditional Spring MVC.
  • Unlike traditional MVC,Controlleruse@RestController, directly return a Java object, not a view.
  • Spring Boot automatically serializes the returned object to JSON or XML.
@RestController
public class UserController {
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") int id) {
        // Get user information from the service layer        return (id); // Returns the User object, not the view name    }
}

Traditional Spring MVC Return to View

  • What is returned is a view file (such as a JSP page) that renders dynamic HTML via server side.
  • Controller returnsModelAndViewObject, containing view name and model data.
  • Render views using JSP, Thymeleaf, etc.

Spring Boot RESTful API

  • Returns data in JSON or XML format, and is rendered by the front-end or client.
  • use@RestController, the controller returns the object directly, and Spring Boot automatically converts it to JSON.

Summarize

The entire process of Spring MVC can be simply summarized into the following steps:

  1. The user sends a request toDispatcherServlet
  2. DispatcherServletuseHandlerMappingFind the corresponding controller.
  3. The controller processes the request and generatesModelAndView
  4. DispatcherServletuseViewResolverResolve the view name.
  5. Pass the model data to the view for rendering.
  6. Returns the rendered view to the user.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.