One, small knowledge classroom

1. The browser displays only HTML files

When the browser requests a JSP dynamic file, the browser just shows the action and does not compile the JSP file. So the compilation work is completed by the server, JSP files in the code, parameters and all completed after the compilation, the formation of a pure HTML format file response to the browser display. (You can read the Tomcat source code if you are interested.)

2. How do I access server resources

In traditional development patterns, we assign each servlet a unique servlet-mapping by declaring servlets in a web.xml file. The browser responds by accessing servlet-mapping to find the corresponding servlet.

<servlet>
    <servlet-name>OneServlet</servlet-name>
    <servlet-name>com.shang.controller</servlet-name>
</servlet>
<servlet-mapping>
    <servlet-name>OneServlet</servlet-name>
    <url-pattern>/one</url-pattern>
</servlet-mapping>
Copy the code

What are the pain points in the traditional development mode

An HttpServlet requires an entry in web.xml, which is difficult to maintain when there are too many.

SpringMVC has designed a DispatchServlet to combine traditional development patterns with its own. It only needs to configure one Servlet in web.xml, that is DispatchServlet, as an entry point to the SpringMVC container. The DispatchServlet acts as a scheduler.

An HttpServlet can only handle one HTTP request, and an application needs to create a large number of HttpServlet classes, which are difficult to maintain.

SpringMVC uses @Controller + @RequestMapping to replace the traditional development model where an HttpServlet can handle only one HTTP request.

Third, DispatchServlet

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
   try {
      try {
         // Get HandlerExecutionChain (Handler + HandlerInterceptor) from request
         mappedHandler = getHandler(processedRequest);

         // Step 2: Find the appropriate HandlerAdapter according to the handler.
         // mappedHandler.gethandler () gets the handler for the current request
         HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
         
         // Step 3: Execute the preHandle() method on all HandlerExecutionChain HandlerInterceptor,
         // Decide whether to proceed based on the result returned by the interceptor.
         if(! mappedHandler.applyPreHandle(processedRequest, response)) {return;
         }
         // Step 4: Execute the handler() method through the HandlerAdapter to return the ModelAndView
         mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

         applyDefaultViewName(processedRequest, mv);
         // Step 5: Execute all HandlerInterceptor postHandle() methods in HandlerExecutionChain
         mappedHandler.applyPostHandle(processedRequest, response, mv);
      }
      catch (Exception ex) {
         dispatchException = ex;
      }
      catch (Throwable err) {
         // support methods annotated with @ExceptionHandler annotations
         dispatchException = new NestedServletException("Handler dispatch failed", err);
      }
      // Step 6: Final processing, first parse ModelAndView or Exception into ModelAndView, then view.render()
      The // method merges the page with static attributes and the request field to return a pure HTML file to the browserprocessDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); }}Copy the code

Four, nine components

SpringMVC is dedicated, has clear responsibilities, and is easy to scale.

// The onRefresh() method is called back when the container is refreshed
protected void onRefresh(ApplicationContext context) {
   initStrategies(context);
}
// Policy pattern to initialize nine Components of SpringMVC
protected void initStrategies(ApplicationContext context) {
   // File handler: handles file upload requests
   initMultipartResolver(context);
   // Localization handler: internationalization processing
   initLocaleResolver(context);
   // Theme processor: such as Spring Festival theme, Christmas theme. A theme corresponds to a Properties file, which houses
   // All resources related to the current topic, such as images, CSS styles, etc
   initThemeResolver(context);
   // Handler mapper: finds the corresponding handler based on the URL
   initHandlerMappings(context);
   // Processor adapter: Adapter mode, for different requests through the appropriate handler.
   initHandlerAdapters(context);
   Exception handler: Specialises in handling exceptions in SpringMVC
   initHandlerExceptionResolvers(context);
   // View name translator: Generates a default viewname if the programmer does not define a view or viewname in the handler
   initRequestToViewNameTranslator(context);
   // View parser: used to parse String View names and Locale into View views
   initViewResolvers(context);
   // Parameter Transfer manager: used to manage flashmaps, which are used to redirect parameters
   initFlashMapManager(context);
}
Copy the code

1. HandlerMapping

Because SpringMVC is componentized, you need a component to find the handler through request. Depending on how the lookup is done, the programmer needs to configure the desired processor mapper himself. Commonly used are as follows:

BeanNameUrlHandlerMapping: based on the controller instance beanName mapping. SimpleUrlHandlerMapping: Supports mapping controller instances by URL. RequestMappingHandlerMapping: support @ Controller annotationCopy the code

2.HandlerAdapter

Because SpringMVC has a variety of different handlers (controllers), an Adpater is required to accommodate existing handlers. So programmers need to configure the appropriate processor adapter themselves. As follows:

SimpleServletHandlerAdapter: support implementation Servlet interface handler SimpleControllerHandlerAdapter: Support to implement the Controller interface handler HttpRequestHandlerAdapter: support implementation HTTPRequestHandler interface handler RequestMappingHandlerAdapter: Supports @Controller, which can handle handlers of type HandlerMethod.Copy the code

3. ViewResolver

The ViewResolver transforms the logical view into a physical view that the user can see without the programmer having to write a long page path each time, so the programmer needs to configure the ViewResolver appropriately. SpringMVC parses the logical View path in ModelAndView into View objects through ViewResolver, and the View objects render the View and respond to the browser in pure HTML format.

InternalResourceViewResolver: support JSP view VelocityViewResolver: support processing Velocity FreeMarkerViewResolver view: support processing FreeMarker viewCopy the code

Five, the summary

Now that you’ve read this, you have a clear idea of SpringMVC’s important working components and how SpringMVC processes them. What about the details of each component’s initialization and how it works? With these questions in mind, we went straight to the source code.

  • HandlerMapping source code interpretation.
  • Second: HandlerAdapter source code interpretation.
  • ViewResolver source code interpretation.