1. 程式人生 > >Spring 學習(五)--- 處理請求的過程Servlet

Spring 學習(五)--- 處理請求的過程Servlet

tom interact jvm answer ack connector ger zed spa

文章部分圖片和句子來自參考資料,閱讀前先閱讀參考資料



servlet 介紹

servlet 類



servlet 與 Tomcat 交互

下文分七步闡述了 servlet 與 Tomcat 的交互,同時也是 servlet 的生命周期。

As managed components, servlets have a life cycle, which begins when the managing container loads the servlet class, usually in response to a request, and ends when the container closes the servlet by calling the "destroy" method. All the servlet‘s activity between these two points is considered part of its life cycle.

The lifecycle of a typical servlet running on Tomcat might look something like this:

  1. Tomcat receives a request from a client through one of its connectors.
  2. Tomcat maps this request to the appropriate Engine for processing. These Engines are contained within other elements, such as Hosts and Servers, which limit the scope of Tomcat‘s search for the correct Engine.
  3. Once the request has been mapped to the appropriate servlet, Tomcat checks to see if that servlet class has been loaded. If it has not, Tomcat compiles the servlet into Java bytecode, which is executable by the JVM, and creates an instance of the servlet.
  4. Tomcat initializes the servlet by calling its init method. The servlet includes code that is able to read Tomcat configuration files and act accordingly, as well as declare any resources it might need, so that Tomcat can create them in an orderly, managed fashion.
  5. Once the servlet has been initialized, Tomcat can call the servlet‘s service method to process the request, which will be returned as a response.
  6. During the servlet‘s lifecycle, Tomcat and the servlet can communicate through the use of listener classes, which monitor the servlet for a variety of state changes. Tomcat can retrieve and store these state changes in a variety of ways, and allow other servlets access to them, allowing state to be maintained and accessed by various components of a given context across the span of a single or multiple user sessions. An example of this functionality in action is an e-commerce application that remembers what the user has added to their cart and is able to pass this data to a checkout process.
  7. Tomcat calls the servlet‘s destroy method to smoothly remove the servlet. This action is triggered either by a state change that is being listened for, or by an external command delivered to Tomcat to undeploy the servlet‘s Context or shut down the server.



參考資料

  • 知乎_servlet本質
  • An Introduction to Tomcat Servlet Interactions
  • How Spring Web MVC Really Works

Spring 學習(五)--- 處理請求的過程Servlet