菜鸟学习 Spring 之 DispatcherServlet
2019-04-27 本文已影响0人
醉疯觞
写在前面
关于 DispatcherServlet
已经有很多博客,这里可以说是一篇整理文章然后加了一些自己的理解。
说到 DispatcherServlet
就不得不提到 Servlet
,所以下面主要讲讲 Servlet
Servlet 生命周期
关于 Servlet
周期,这里结合源码注释进行说明:
package javax.servlet;
public interface Servlet {
/**
* The servlet container calls the <code>init</code> method exactly once
* after instantiating the servlet. The <code>init</code> method must
* complete successfully before the servlet can receive any requests.
*
* 大意就是 servlet 容器会在实例化时调用一次(仅此一次)init 方法
* 调用完成后才可以接收请求
*
*/
public void init(ServletConfig config) throws ServletException;
/**
* Called by the servlet container to allow the servlet to respond to a
* request.
*
*
* This method is only called after the servlet's <code>init()</code> method
* has completed successfully.
*
* servlet 容器调用 service 方法响应请求,并且该方法只能在 init 方法调用成功后才能被调用。
*
*/
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
/**
* Called by the servlet container to indicate to a servlet that the servlet
* is being taken out of service. This method is only called once all
* threads within the servlet's <code>service</code> method have exited or
* after a timeout period has passed. After the servlet container calls this
* method, it will not call the <code>service</code> method again on this
* servlet.
*
*
* 大意就是说,这个方法被调用后,会等待容器内所有线程执行 service 方法完毕
* 或超时(并且容器不会再接收请求调用 service 方法),才执行方法内容。
*
*/
public void destroy();
public ServletConfig getServletConfig();
public String getServletInfo();
}
由源码可知,Servlet
生命周期:

前端总控制器模式
前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。参考1、参考2。

从图中可以看出请求进来之后,统一由 FrontController
处理,再委托给相应的应用控制器,ApplicationController
再调度获得结果。是不是感觉Spring MVC
呼之欲出?
Spring MVC
从前端总控制器模式就能看出点端倪,Spring MVC
就是在其之上设计的。DispatcherServlet
就是 FrontController
,我们经常写的 @Controller
等方法则是 ApplicationController
,从而完成整个MVC
模式实现。
DispatcherServlet 运行链路

类图可以看到 DispatcherServlet
最后还是实现了 Servlet
接口,也就是意味着它始终会遵循 Servlet
运行生命周期。
DispatcherServlet init
调用链路:

DispatcherServlet service
调用链路:

DispatcherServlet destroy
调用链路:

END
这篇文章只能是一个总览,让自己对 Spring MVC
有个整体概念。从中我们可以了解其完全在 Servlet
基础上进行设计,并且尽可能的利用。
最后,期待自己能够完成这个系列的学习。