6.10、请求映射原理 - 图1

    SpringMVC功能分析都从 org.springframework.web.servlet.DispatcherServlet-》doDispatch()

    1. protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    2. HttpServletRequest processedRequest = request;
    3. HandlerExecutionChain mappedHandler = null;
    4. boolean multipartRequestParsed = false;
    5. WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    6. try {
    7. ModelAndView mv = null;
    8. Exception dispatchException = null;
    9. try {
    10. processedRequest = checkMultipart(request);
    11. multipartRequestParsed = (processedRequest != request);
    12. // 找到当前请求使用哪个Handler(Controller的方法)处理
    13. mappedHandler = getHandler(processedRequest);
    14. //HandlerMapping:处理器映射。/xxx->>xxxx
    15. ...
    16. }

    getHandler()方法如下:

    1. @Nullable
    2. protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    3. if (this.handlerMappings != null) {
    4. for (HandlerMapping mapping : this.handlerMappings) {
    5. HandlerExecutionChain handler = mapping.getHandler(request);
    6. if (handler != null) {
    7. return handler;
    8. }
    9. }
    10. }
    11. return null;
    12. }

    this.handlerMappings在Debug模式下展现的内容:
    image.png
    RequestMappingHandlerMapping:保存了所有@RequestMapping 和handler的映射规则。
    image.png
    所有的请求映射都在HandlerMapping中。

    • SpringBoot自动配置欢迎页的 WelcomePageHandlerMapping 。访问 /能访问到index.html;
    • SpringBoot自动配置了默认 的 RequestMappingHandlerMapping
    • 请求进来,挨个尝试所有的HandlerMapping看是否有请求信息。
      • 如果有就找到这个请求对应的handler
      • 如果没有就是下一个 HandlerMapping
    • 我们需要一些自定义的映射处理,我们也可以自己给容器中放HandlerMapping。自定义 HandlerMapping