Spring's web framework is built on the Servlet API and deployed on its own embedded Servlet container. Centered around its Dispatcher Servlet, Spring MVC handles much of the complexity of the request-response cycle.
- Model: The data being passed, rendered, and manipulated
- View: What will be displayed, usually as html
- Controller: Handles logic, routing
- Request sent to
DispatcherServlet DispatcherServletcallsHandlerMappingfor help with request URIHandlerMappinglooks up the handler for the URI, a registeredControllerwhich is returned to theDispatcherServletand calledControlleris the entry-point for an event in and out of the rest of the programControllerreturns aViewname &Modelto theDispatcherServletDispatcherServletconsultsViewResolverto interpretViewname as a template file and weave theModelinto the response body- Response sent to client
Spring MVC's front controller has its own WebApplicationContext, allowing it to handle more bean scopes than singleton and prototype. It manages Controllers, HandlerMapping, ViewResolver, and all other components.
While configurable using RequestMappingHandlerMapping objects, it can be simply enabled using a <mvc:@annotation-driven/> element tag in configuration, allowing for component scanning to automatically register all @Controller and similar beans along with their mappings. It is responsible for routing requests to specific methods within these controllers.
A @Controller stereotype annotation registers a class as a library of methods mapped to URI paths to handle requests. Several related annotations help to further specify these requests and their expected responses.
@RequestMappingspecifies the URI with attributes like value for the path and method for the HTTP verb, and can be defined at the class or method level.@GetMappingis a shorthand form of a@RequestMappingwith GET assumed as its method. Also has siblings in@PostMappingand similar annotations.@RequestParamcan be used on method parameters to bind form or query attributes to arguments.@PathVariablecan be used on method parameters to bind URI path variables to arguments.@ResponseBodytags a method (or all methods of a class) to write their return objects directly to the response body, skipping the ViewResolver entirely.
ViewResolvers handle server-side view resolution for static HTML/CSS/JS files, or rendering for dynamic templates like JSPs or Thymeleaf files.