菜鸟学习 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 基础上进行设计,并且尽可能的利用。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值