[Servlet] 3: The basic principle of Servlet, the life cycle of Servlet object

Table of contents

Chapter 5 | Dynamic Resources and Servlets

| Chapter Overview

| The principle and relationship between Tomcat and Servlet

The basic composition of TomcatEdit

Server handles HTTP requests

Connector internal architecture analysis

Container internal architecture analysis

Summary of Tomcat's execution process

| Servlet overview, interface implementation

Basic overview of Servlet

Implement the Servlet interface and access it through URL: four steps

IDEA generates Servlet implementation class with one click

| Servlet object cycle and load-on-startup


This article belongs to the third part of the back-end full set of notes

(Updating) [Getting started with the back end and getting into the soil! 】Java+Servlet+JDBC+SSM+SpringBoot+SpringCloud Basic Introduction_m0_57265007's Blog - An article on the CSDN blog, from getting started with the back end to entering the soil. Contains Java Basic + Advanced, MySQL, JDBC, Servlet, SSM, SpringBoot, SpringCloud, project notes. https://blog.csdn.net/m0_57265007/article/details/127962617?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22 %3A%22127962617%22%2C%22source%22%3A%22m0_57265007%22%7D

Chapter 5 | Dynamic Resources and Servlets

| Chapter Overview

In this chapter you will learn

  • Through the basic principles of Tomcat, the basic principles of Servlet (theoretical basis) are introduced

  • Master a series of steps for Servlet to create its implementation class in IDEA, register and configure the implementation class to Tomcat, deploy, and access. At the same time, learn to use IDEA to quickly generate Servlet class knocks

  • The life cycle of the Servlet object, when it is created, and load-on-time parameters

  • HttpServletRequest parses the HTTP request and sends it to the server

  • HttpServletResponse responds to HTTP requests

  • Data Sharing Between Multiple Servlets

  • Rules for Calling Between Multiple Servlets


| The principle and relationship between Tomcat and Servlet

The basic composition of Tomcat

1. The top-level container in Tomcat is Server, which represents the entire server. A Server can contain at least one Service, which is used to provide specific services.

2. Service mainly consists of two parts: Connector and Container. The heart of Tomcat is these two components. The functions of these two components: Connector is used to handle connection-related matters, and provides Socket and Request and Response-related transformations; Container is used to encapsulate and manage Servlets, and specifically handle Request requests.

3. There is only one Server in a Tomcat, a Server can contain multiple Services, and a Service has only one Container, but it can have multiple Connectors, because a service can have multiple connections, such as providing Http and Https links at the same time, can also provide Connections to different ports of the same protocol.

4. Multiple Connectors and a Container form a Service. With a Service, you can provide services to the outside world, but a Service needs a living environment. Someone must be able to give her life and control her life and death, then it is not a Server No way! So the entire life cycle of Tomcat is controlled by Server. In addition, the above inclusion relationship or parent-child relationship can be seen in the server.xml configuration file under the conf directory of tomcat.

5. The port number set on the Server label is 8005 (Note: the port number 8005 of the Server label is used to monitor the Server interface of Tomcat; and the Tomcat port 8080 is used to monitor HTTP requests from the outside. The two are different concepts!) , shutdown="SHUTDOWN" means listening to the "SHUTDOWN" command on port 8005, and shutting down Tomcat if received. A Server has a Service, and of course it can be configured. There are multiple Services. The content on the left of the Service belongs to the Container, and the Connector below the Service.


Server handles HTTP requests

1. The user enters the URL in the browser, and the request is sent to port 8080 of the local machine, and is obtained by the Coyote HTTP/1.1 Connector listening there;

2. The Connector hands the request to the Engine (Container) of the Service where it is located, and waits for the Engine's response;

3.Engine obtains the request localhost/test/index.jsp, which matches all virtual host Hosts;

4. The Engine matches the Host named localhost (even if it does not match, the request is handed over to the Host for processing, because the Host is defined as the default host of the Engine), and the Host named localhost gets the request /test/index.jsp , matching all Contexts it owns. Host matches the Context whose path is /test (if no match is found, the request is handed over to the Context whose path name is " ");

5. The Context with path="/test" obtains the request /index.jsp, and finds the corresponding Servlet in its mapping table. Context matches the Servlet whose URL Pattern is *.jsp, corresponding to the JspServlet class;

6. Construct HttpServletRequest object and HttpServletResponse object, call doGet() or doPost() of JspServlet as parameters, execute business logic, data storage, etc.;

7. Context returns the HttpServletResponse object after execution to Host;

8. Host returns the HttpServletResponse object to Engine;

9. Engine returns the HttpServletResponse object to Connector;

10. Connector returns the HttpServletResponse object to the client Browser.


Connector internal architecture analysis

  • The Connector is used to accept the request and encapsulate the request into Request and Response, and then hand it over to the Container for processing. After the Container is processed, it is handed over to the Connector to return to the client

  • Connector uses ProtocolHandler to process requests, and different ProtocolHandlers represent different connection types


Container internal architecture analysis

(1) Engine: Engine, used to manage multiple sites, a Service can only have one Engine at most;

(2) Host: Represents a site, which can also be called a virtual host, and a site can be added by configuring the Host;

(3) Context: represents an application program, corresponding to a set of programs usually developed, or a WEB-INF directory and the following web.xml file;

(4) Wrapper: Each Wrapper encapsulates a Servlet;

The difference between Context and Host is that Context represents an application, and each folder directory under webapps under the default configuration in our Tomcat is a Context, in which the main application is stored in the ROOT directory, and sub-applications are stored in other directories, and the entire webapps is a Host site.


Summary of Tomcat's execution process

  1. First, use the startup command, after the port number 8005 of the Server label listens to the command, start the service of the Tomcat server

  2. The client initiates a request, Tomcat's port 8080 receives the request, and starts a series of processing

  3. When a request is sent to Tomcat, it first goes through the Service and then it is handed over to the Connector. The Connector is used to receive the request and encapsulate the received request into Request and Response for specific processing. After the Request and Response are encapsulated, they are handed over to the Servlet in the Container. Processing, the Container returns to the Connector after processing the request, and finally the Connector returns the processing result to the client through the Socket, so that the entire request is processed!

  4. The bottom layer of Connector uses Socket to connect, Request and Response are encapsulated according to HTTP protocol, so Connector needs to implement TCP/IP protocol and HTTP protocol at the same time!

  • Finally, to summarize:

    (1) There is only one Server in Tomcat, and a Server can have multiple Services (for providing specific services), a Service can have multiple Connectors (because a service can have multiple connections) and a Container; (2) Server is in charge (4) Service is to provide external services; (5) Connector is used to accept requests and encapsulate them into Request and Response for specific processing; (6) Container is used to encapsulate and manage Servlets, as well as specific Handle the request request;


| Servlet overview, interface implementation

Basic overview of Servlet

  • As mentioned earlier, Servlet is an interface in Wrapper in Container in Tomcat. For programmers, there is no need to go deep into the underlying implementation of Tomcat. We only need to know: Java web development, to a large extent, is operating the Servlet interface in Tomcat: writing the code of the Servlet implementation class, configuring the mapping relationship between the Servlet implementation class object and the URL in the Tomcat website core configuration file web.xml, etc. wait……

  • A Servlet in a narrow sense refers to an interface implemented by the Java language, and a Servlet in a broad sense refers to any class that implements the Servlet interface. Generally, people understand Servlet as the latter. Servlets run on application servers that support Java. In principle, Servlet can respond to any type of request, but in most cases Servlet is only used to extend the Web server based on HTTP protocol.

  • The role of servlets:

    • In the Servlet specification, specify the [Dynamic Resource File] development steps

    • In the Servlet specification, specify the Http server to call the dynamic resource file rule

    • In the Servlet specification, specify the Http server management dynamic resource file instance object rule

  • There is a servlet-api.jar in the lib file in the Tomcat server directory. This is the jar package of the Servlet interface~

  • In the Servlet specification, the [Dynamic Resource File] that can be invoked by the HTTP server (Tomcat) must be a Servlet interface implementation class


Implement the Servlet interface and access it through URL: four steps

[Preliminary preparation] Create a web Module

Step1. Create a normal Java Module

Step2. Right-click the module and add WEB framework support. Click OK to create a website

[Step1] Write a class to implement the HttpServlet interface

  • Generally, it inherits the already written implementation class HttpServlet of the Servlet interface, rather than directly implements the Servlet interface. The purpose is to simplify the number of methods that need to be rewritten and reduce the difficulty of development

  • If you have not imported the Jar package of the Servlet class, you can press Ctrl+Alt+Shift+S to open Project Structure - Module - the corresponding Module. Add Servlet.jar under the Tomcat directory/lib

//src/controller/MyServlet.java
public class MyServlet extends HttpServlet {
}

[Step2] Rewrite the doGet( ) or doPost( ) method of HttpServlet as needed

  • Shortcut key in IDEA: Ctrl+O select doGet and doPost

  • The requests sent through the browser URL are all GET requests, here only GET can be rewritten (POST requests are generally controlled by the front-end method, or redirection control

[Directory structure is the same as Step1]

//src/controller/MyServlet.java
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp); 如果你是要彻底覆盖父类的doGet方法,不需要父类提供的功能,就可以删除super.doGet(req,resp);这一句
        System.out.println("这是Servlet的doGet方法");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
    }
}

[Step3] In the web.xml configuration file, register the developed java class to the web server (Tomcat)

  • The role of web.xml is mainly to: specify the path corresponding to the Servlet implementation class, the object name, and the name of the URL corresponding to the object name

  • The path and object name of the Servlet implementation class are written in <servlet> </sevlet>

    The mapping between the object name and URL of the Servlet implementation class is written in <servlet-mapping> </servlet-mapping>

    Error-prone: Aliases in < url-pattern>/web1 </url-pattern> must start with / ! ! ! !

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    
    <!--在Tomcat目录下的【网站核心配置文件 web.xml】,注册Servlet的实现类-->
    <servlet>
        <servlet-name>MyServletName</servlet-name><!--【Servlet实现类的对象】的名字(动态代理 自动生成)-->
        <servlet-class>controller.MyServlet</servlet-class><!--【Servlet实现类】相对于src的路径-->
    </servlet>
    <!--将刚才注册的Servlet实现类的【对象名】对应网站中【作为url时的别名】-->
    <servlet-mapping>
        <servlet-name>MyServletName</servlet-name>
        <url-pattern>/web1</url-pattern><!--若当URL中有/web1:当Tomcat收到之后,会到web.xml中寻找对应的Servlet实现类对象名,然后动态代理根据其对应的类路径生成对象,执行业务代码-->
    </servlet-mapping>
    
</web-app>

[Step4] Deploy the website to the web server (Tomcat): Run – Edit Configuration – Deploy

The deployment steps are the same as IDEATomcat static resource website access

Then after deployment, enter the browser to access


IDEA generates Servlet implementation class with one click

  • Before one-click generation, you need to ensure that the current Mudule (Ctrl+Alt+Shift+S to open Project Structure) has imported the Servlet package

Right-click and select Servlet (note that the package of the Servlet implementation class is generally under the controller)

  • If you don't find a Servlet option, it is recommended that you create it honestly...it's not troublesome anyway.

  • There is no solution for Servlet in the options (not recommended, it will destroy the directory structure, for reference only) References

 

| Servlet object cycle and load-on-startup

Servlet object life cycle

  1. The instance objects of all Servlet interface implementation classes in the website can only be created by the Http server . Developers cannot manually create instance objects of Servlet interface implementation classes

  2. During the running of the Http server, a Servlet interface implementation class can only create one instance object , but it can be executed multiple times (that is, accessed multiple times by URL)

  3. After the Http server is closed, all Servlet objects in the website are automatically destroyed

Servlet object creation timing & load-on-startup configuration parameters

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>MyServletName</servlet-name>
        <servlet-class>controller.MyServlet</servlet-class>
        <load-on-startup>0</load-on-startup><!--填写一个大于0的整数即可。Tomcat会在启动后自动创建Servlet实现类对象。数字代表创建优先级-->
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServletName</servlet-name>
        <url-pattern>/web1</url-pattern>
    </servlet-mapping>
</web-app>

  • The timing of the creation of the Servlet object (that is, the timing of initialization)

    • If the load-on-startup parameter is not configured for the corresponding Servlet object in web.xml, the container will generally create the object when responding to the web request for the first time, and will first check whether the servlet is initialized. If not, call the init of the servlet () Initialize first, and then respond to the request after the initialization is successful.

    • If the load-on-startup parameter is configured, the servlet will create the corresponding implementation class object immediately after Tomcat starts startup , but only call the init() method of the servlet to initialize the resources related to the servlet. After successful initialization, the servlet can respond to web requests

  • The role of the load-on-startup parameter

    • Flags whether the container should load this servlet at startup.

    • The value in the middle must be an integer .

    • When > =0, it means that the container will initialize the servlet class when it starts . The smaller the value, the higher the priority and the earlier the loading

      When < 0, it means that the servlet class will be instantiated when it is called .

    • If we set multiple servlets in web.xml , we can use load-on-startup to specify the loading order of servlets , and the server will initialize the servlets in turn according to the size of load-on-startup. However, even if we repeat the load-on-startup setting, there will be no exception, and the server will decide the initialization order by itself.

Verify that "the Servlet object can only be created once, but can be called multiple times" and verify that load-on-startup can indeed change the creation timing of the Servlet implementation class

  • The init() method can be understood as the construction method when the Servlet implementation class is created

//src/controller/MyServlet.java
public class MyServlet extends HttpServlet {

	//可以重写 init 方法,这个init方法代表对象被创建时候调用初始化。
    @Override
    public void init() throws ServletException {
    	super.init();
        System.out.println("MyServlet对象被创建了");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--在Tomcat目录下的【网站核心配置文件 web.xml】,注册Servlet的实现类-->
    <servlet>
        <servlet-name>MyServletName</servlet-name><!--【Servlet实现类的对象】的名字(动态代理 自动生成)-->
        <servlet-class>controller.MyServlet</servlet-class><!--【Servlet实现类】相对于src的路径-->
        <load-on-startup>0</load-on-startup><!--填写一个大于0的整数即可。Tomcat会在启动后自动创建Servlet实现类对象。数字代表创建优先级-->
    </servlet>
    <!--将刚才注册的Servlet实现类的【对象名】对应网站中【作为url时的别名】-->
    <servlet-mapping>
        <servlet-name>MyServletName</servlet-name>
        <url-pattern>/web1</url-pattern><!--若当URL中有/web1:当Tomcat收到之后,会到web.xml中寻找对应的Servlet实现类对象名,然后动态代理根据其对应的类路径生成对象,执行业务代码-->
    </servlet-mapping>
</web-app>

Validation results:

  • If the load-on-startup parameter is configured as an integer >=0 in the web.xml configuration of the Servlet

    • Then click to run Tomcat and find that "MyServlet object is created" is output immediately

    • Enter /web1 in the URL of the webpage, and find that "the code execution result in doGet" is output

    • After visiting /web1 in the URL many times later, it was found that the execution result of doGet could be output, but "MyServlet object was created" never appeared again

    • The above phenomenon shows that the Servlet object can only be created once, but can be accessed multiple times .

      It also shows that if the load-on-startup parameter>=0, the Servlet implementation class object will be created immediately when Tomcat starts

  • If the load-on-startup parameter is not configured in the web.xml configuration of the Servlet

    • Then click to run Tomcat and find that there is no output (meaning that the Servlet object has not been initialized, that is, the object has not been created)

    • Enter /web1 for the first time in the webpage URL, and find that "MyServlet object is created" and "code execution result in doGet" are output

    • The above phenomenon shows that if the Servlet object is configured with the load-on-startup parameter, it will be created immediately when Tomcat starts, otherwise it will only be created when it is used for the first time

Guess you like

Origin blog.csdn.net/m0_57265007/article/details/128005739