【每日一篇】Servlet/tomcat/spring mvc之间关系

        首先,什么是Servlet?狭义的说,Servlet是JAVA提供的Servlet接口,我们可以看一眼Servlet接口的定义:

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
The servlet is constructed, then initialized with the init method.
Any calls from clients to the service method are handled.
The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.

      简而言之,就是说Servlet是一个小型的JAV程序,运行在Web 服务器中来处理用户的请求,我们实际上使用的各路Servlet都需要通过各种方式实现这个接口。

     然后Servlet接口提供了5个方法:初始化init,销毁destory,处理请求service,获取Servlet参数getServletConfig,获取Servlet信息getServletInfo。当然主要的方法还是前三个方法,体现了servlet的生命周期,从容器创建时要做什么的init,处理请求并返回时做什么的service,到请求结束后销毁servlet做什么的destory.

       然后,什么是tomcat?尽管tomcat非常灵活而强大,可以作为web应用服务器,但是tomcat首先是一个Servlet容器,Servlet容器可以对Servlet进行管理,控制其生命周期。使其可以专注于自己应该做的事情,不需要考虑端口啊多线程啊socket之类的东西,也使得Servlet在各种环境下具有适应性。

    一个基本的流程:tomcat接收请求,找到合适的Servlet来处理请求,如果该Servlet没加载,就顺便编译加载到JVM,如果加载了,就调init方法初始化,调Service方法处理request并返回responser,观测Servlet状态变化,在结束时调用destory方法。

    接下来,什么是SpringMVC呢,这是Spring提供的一个mvc框架,通过把保存了数据Map的Model,页面显示的View,控制器Controller三者分离,简化了web项目开发的复杂度,降低了分工的难度。

    Spring Boot将tomcat设为默认容器,tomcat是一个Servlet容器,所以Spring MVC的入口也毫无意外的是一个Servlet,也就是前置控制器DispatcherServlet,作为Spring MVC架构的核心,前置控制器能够拦截请求,将其分发给Controller处理。

你可能感兴趣的:(JAVA)