菜鸟学习 Spring 之 DispatcherServlet 总览

写在前面

关于 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 生命周期:

Servlet 生命周期
前端总控制器模式

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

前端总控制器

从图中可以看出请求进来之后,统一由 FrontController 处理,再委托给相应的应用控制器,ApplicationController 再调度获得结果。是不是感觉Spring MVC呼之欲出?

Spring MVC

从前端总控制器模式就能看出点端倪,Spring MVC就是在其之上设计的。DispatcherServlet 就是 FrontController,我们经常写的 @Controller 等方法则是 ApplicationController,从而完成整个MVC模式实现。

DispatcherServlet 运行链路
DispatcherServlet

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

DispatcherServlet init调用链路:

init

DispatcherServlet service调用链路:

service

DispatcherServlet destroy调用链路:

destroy
END

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

最后,期待自己能够完成这个系列的学习。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring MVC 1、简介 1.1 Web MVC 在Web开发中,通常是浏览器发送请求到服务器,由服务器接收...
    开发者如是说阅读 3,051评论 0 5
  • IOC 控制反转容器控制程序对象之间的关系,而不是传统实现中,有程序代码之间控制,又名依赖注入。All 类的创建,...
    irckwk1阅读 4,594评论 0 0
  • 本章内容: 映射请求到Spring控制器 透明地绑定表单参数 校验表单提交 状态管理、工作流以及验证都是Web 开...
    谢随安阅读 12,734评论 0 4
  • 16. Web MVC 框架 16.1 Spring Web MVC 框架介绍 Spring Web 模型-视图-...
    此鱼不得水阅读 4,693评论 0 4
  • 对于java中的思考的方向,1必须要看前端的页面,对于前端的页面基本的逻辑,如果能理解最好,不理解也要知道几点。 ...
    神尤鲁道夫阅读 4,237评论 0 0