本文分析请求分析的映射原理
在进行web开发的时候,每一个请求都会发送到SpringBoot的底层源码中,我们知道SpringBoot中每个请求都会来到DispatcherServlet,底层还是使用SpringMVC,所以我们来看DispatcherServlet类。
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
继承了HttpServlet,那么一定会重写doGet()和doPost()方法。其中在HttpServlet类中的方法如下:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_post_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_get_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
而子类DispatcherServlet类中没有重写doGet()和doPost()方法,那么我们就查看FrameworkServlet类,发现重写了方法,源码如下:
// 在新版的springboot中,重写的@override没写
protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.processRequest(request, response);
}
protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.processRequest(request, response);
}
重写的方法中都调用了processRequest()方法,再查看processRequest()方法的源码,:该方法中前面是一些初始化的数据,重点看doService方法,该方法的核心就是调用了doService()方法来处理请求和响应。
进入到这个doService()方法,里面是一个抽象类。
protected abstract void doService(HttpServletRequest request, HttpServletResponse response) throws Exception;
然后点击前面,实现这个抽象类的具体实现。在DispatcherServlet中。
在这个方法中,重点看doDispatch方法,它来进行请求的调用和响应。
this.doDispatch(request, response);
在doDispatch方法中,可以看到request中是有coyoteRequest看到它的请求。
下面看看如何找到对应的controller层处理当前请求的方法。在这一行的代码

进入到这个方法中,查看具体是如何找到的。
这是handlerMapping,这是一个处理器映射器,SpringMVC根据它中的映射规则知道了哪个请求应该由哪个处理器(就是我们自己写的控制器类)处理。默认的handlerMapping有5个(如图),其中第一个RequestMappingHandlerMapping中保存了@RequestMapping和handler的映射规则。当我们的应用一启动,SpringMVC自动扫描所有的Controller并解析注解,把注解信息保存在handlerMapping里面。 然后通过循环遍历着5个handlerMapping,看哪个可以处理当前请求。
controller中写的路径都存到了Map里面。然后通过mapping.getHandler(request)把请求对应的handler找到(也就是controller中对应的方法)完成映射。