Servlet annotations and life cycle and ServletConfig interface in JavaWeb


Nothing is easy in the world, there are many people who want to be lazy, so there is a shortcut

Just like: There is no road in the world, if there are many people walking, it becomes a road


 ——Lungcen

 

Table of contents

Servlet annotations

@WebServlet annotation (Servlet annotation)

Attributes of the @WebServlet annotation

 load-on-startup element

 Use of @WebServlet annotation

Precautions

Advantages and disadvantages of @WebServlet annotation and web.xml

Servlet life cycle

initialization phase

load and instantiate

 Call the init() method to initialize

runtime phase

Destruction phase

Lifecycle Execution Process

 Servlet virtual path mapping

single mapping 

multiple mapping

Virtual Path Matching Rules

full path match

 directory match

extension match

default match (default match)

 ServletConfig interface

Get the ServletConfig object

Methods provided by the ServletConfig interface



Servlet annotations


@WebServlet annotation (Servlet annotation)

In Servlet, web.xml plays a very important role. It can centrally manage the configuration of all Servlets. However, if there are many Servlets in the project, the configuration of web.xml will become very lengthy.

So in order to simplify the configuration of Servlet, annotation support has been added in Servlet 3.0

Attributes of the @WebServlet annotation

@WebServlet is used to declare a class as a Servlet. This annotation will be processed by the container during deployment, and the container will deploy the corresponding class as a Servlet according to its specific attribute configuration.

name ---> <servlet-name>
value ---> <url-pattern>
urlPatterns ---> <url-pattern>
loadOnStartup ---> <laod-on-startup>
name String Specifies the name attribute of the servlet. If not specified explicitly, the value is the fully qualified name of the Servlet, that is, package name + class name.
value String[] This attribute is equivalent to the urlPatterns attribute, and both cannot be specified at the same time. If specified at the same time, the value of value is usually ignored.
urlPatterns String[] Specifies a set of URL matching patterns for servlets.
loadOnStartup int Specifies the loading order of servlets.
initParams WebInitParam[] Specify a set of Servlet initialization parameters
asyncSupported boolean Declares whether the servlet supports the asynchronous mode of operation.
description String Specify the description information of this Servlet.
displayName String Specifies the display name of the servlet.

 load-on-startup element

load-on-startup is used to mark whether to initialize the current Servlet when the Servlet container starts, and the initialization sequence of the current Servlet.

Element value rules: Its value must be an integer; 

(Lazy loading) When the value is less than 0 or not specified, it means that the container will be loaded when the Servlet is requested for the first time

(Hungry loading) When the value is greater than 0 or equal to 0, it means that the container loads and initializes the Servlet at startup

                The smaller the value, the higher the priority;

                When the values ​​are the same, the container will choose its own order to load.

 Use of @WebServlet annotation

 There is an attribute in the top-level tag of web.xml: metadata-complete, which is used to specify whether the current web.xml is complete. If this property is set to true, the container will only rely on web.xml during deployment, ignoring all annotations. If you do not configure this property, or set it to false, it means that annotation support is enabled.

Since the default value of the metadata-complete attribute is false, that is, the Servlet annotation support is enabled by default, so by default, when using this annotation, it is not necessary to create a web.xml file.

@WebServlet(urlPatterns = "/Lun1.do")

@WebServlet(urlPatterns = "/Lun1.do")

This annotation is equivalent to the following XML configuration file 

<servlet>
        <servlet-name>myServlet03</servlet-name>
        <servlet-class>com.zpark.servlet.MyServlet03</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>myServlet03</servlet-name>
        <url-pattern>/Lun1.do</url-pattern>
    </servlet-mapping>

very big dividing line


@WebServlet(
        urlPatterns = "/Lun1.do",
        initParams = {@WebInitParam(name = "name", value = "Lungcen"),
                @WebInitParam(name = "pass", value = "110120130")
        }
        )

 @WebServlet(
        urlPatterns = "/Lun1.do",
        initParams = {@WebInitParam(name = "name", value = "Lungcen"),
                @WebInitParam(name = "pass", value = "110120130")
        }
        )

This annotation is equivalent to the following XML configuration file 

        <servlet>
            <servlet-name>myServlet03</servlet-name>
            <servlet-class>com.zpark.servlet.MyServlet03</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>myServlet03</servlet-name>
            <url-pattern>/Lun1.do</url-pattern>
        </servlet-mapping>

        <init-param>
            <param-name>name</param-name>
            <param-value>Lungcen</param-value>
        </init-param>

        <init-param>
            <param-name>pass</param-name>
            <param-value>110120130</param-value>
        </init-param>

Precautions

 Servlet classes created by implementing the Serlvet interface or inheriting GenericServlet cannot use the @WebServlet annotation.

Use the @WebServlet annotation to configure the Servlet class, and do not configure the Servlet-related properties in the web.xml file again. If you use web.xml and @WebServlet to configure the same Servlet class at the same time, the value in web.xml cannot be the same as the name value in the annotation, otherwise the container will ignore the configuration in the annotation.

Advantages and disadvantages of @WebServlet annotation and web.xml

@WebServlet annotation configuration Servlet

Advantages: @WebServlet is directly used in the Servlet class, with less code and simple configuration.

           Each class only focuses on its own business logic and does not interfere with other Servlet classes, which is suitable for simultaneous development by multiple people.

Disadvantage: When there are many Servlets, the configuration of each Servlet is distributed in its own class, which is not easy to find and modify.

The web.xml configuration file configures the Servlet

Advantages: Centralized management of Servlet configuration, easy to find and modify.

Disadvantages: The code is cumbersome, not very readable, and not easy to understand.


Servlet life cycle


Life cycle refers to the process of things from creation to destruction. The human life cycle is the process from birth to death. In this process, there must be some events closely related to the life cycle, and these events will occur at a specific moment in the life cycle.

Servlet also has a life cycle, and the life cycle of Servlet is the process from creation to destruction of Servlet.

The life cycle of a Servlet is managed by the Servlet container and is mainly divided into the following three stages:

                initialization phase

                runtime phase

                Destruction phase

Three methods are defined in the javax.servlet.Servlet interface: init(), service(), and destroy(), which are called by the Servlet container at different stages of the Servlet life cycle.

initialization phase

Servlet initialization is the first phase of its life cycle and the basis for the other phases. Only after the initialization is completed can the Servlet process the request from the client.

The Servlet initialization phase is divided into two steps: 1. Load and instantiate the Servlet. 2. Call the init() method to initialize

load and instantiate

Servlet The Servlet container is responsible for loading and instantiating Servlets. When the container starts or requests a Servlet for the first time, the container will read the configuration information in web.xml or @WebServlet, and load the specified Servlet. After loading successfully, the container will instantiate the Servlet through reflection.

Because the Servlet container creates a Servlet instance through Java's reflection API, it needs to call the Servlet's default constructor (default constructor, that is, a constructor without parameters), so when writing a Servlet class, you cannot just provide a constructor with parameters method.

 Call the init() method to initialize

After loading and instantiation is complete, the Servlet container calls the init() method to initialize the Servlet instance.

The purpose of initialization: Let the Servlet instance complete some initialization work before processing the request, such as establishing a database connection, obtaining configuration information, and so on. The init() method can only be called once during the entire lifetime of the Servlet.

During initialization, the Servlet instance can obtain the initialization parameters configured in web.xml or @WebServlet through the ServletConfig object.

runtime phase

The runtime phase is the most important phase in the Servlet life cycle.

When the Servlet container receives a request from the client, the container will create a ServletRequst object and a ServletResponse object for the request, pass them into the service() method as parameters, and call this method to process the request.

It should be noted here that before executing the service() method, the init() method must have been successfully executed.

In the service() method, the Servlet obtains the relevant information and request information of the client through the ServletRequst object. After the request processing is completed, the response information is packaged through the ServletResponse object and returned to the client. When the Servlet container returns the response information to the client, the ServletRequst object and the ServletResponse object will be destroyed.

During the entire life cycle of the Servlet, for each request of the Servlet, the Servlet container will call the service() method once, and create new ServletRequest and ServletResponse objects. That is, the service() method will be called multiple times during the entire life cycle of the Servlet.

Destruction phase

When the Servlet container closes, restarts or removes the Servlet instance, the container will call the destroy() method to release the resources used by the instance, such as closing the database connection, closing the input stream and output stream of the file, etc., and then the instance is deleted by Java collected by the garbage collector.

For each Servlet instance, the destroy() method can only be called once.

Lifecycle Execution Process

1. The browser sends an HTTP request to the Servlet container

2. The Servlet container parses the request by itself

3. After parsing the request, the Servlet creates a Servlet instance

4. The Servlet container calls the init() method of the Servlet

5. The Servlet container calls the servlet() method of the Servlet

6. The instantiated Serclet outputs response information to the Servlet container

7. The Servlet container calls the destroy() method of the Servlet

8. The Servlet container returns the response information to the browser

In the entire life cycle of Servlet, create Servlet instance, init () method and destroy () method are executed only once. Every time a request is received, the servlet will run itself once  

 Servlet virtual path mapping

Above we know to configure Servlet with annotation @WebServlet annotation. Both urlpatterns and value can specify the access path of a Servlet's URl (also called mapping)

single mapping 

@WebServlet(urlPatterns = "/Lun1.do")

multiple mapping

@WebServlet(
        urlPatterns = {"/Lun1.do", "/Lun2.do"}
        )

Virtual Path Matching Rules

There are four types of Servlet virtual path matching rules:

1. Full path matching (the most commonly used type of trans)

2. Directory matching

3. Extension matching

4. Default match (default match)

full path match

Also known as (exact match): start with /, cannot contain wildcard *, must be a complete path

<!-- 完全路径匹配 -->
<servlet-mapping>
<servlet-name>MyServlet1</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

 directory match

A string starting with a / character and ending with /* is often used for path matching

<!-- 目录匹配 -->
<servlet-mapping>
<servlet-name>MyServlet2</servlet-name>
<url-pattern>/abc/my/*</url-pattern>
</servlet-mapping>


<!-- 目录匹配 -->
<servlet-mapping>
<servlet-name>MyServlet3</servlet-name>
<url-pattern>/abc/*</url-pattern>
</servlet-mapping>

extension match

A string starting with a wildcard *., often used for extension matching

<!-- 扩展名匹配 -->
<servlet-mapping>
<servlet-name>MyServlet4</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

default match (default match)

The mapping path is /, indicating that this Servlet is the default Servlet or the default Servlet of the current application

<!--缺省匹配 -->
<servlet-mapping>
<servlet-name>MyServlet5</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

/myservlet/*.do

This is a very serious logic error. Although the logic is fine in our thinking, * is a wildcard, which, as the name suggests, can represent the front, so this logic is in conflict!

If you want to access the static resources and pictures of the project, you need to delete the default matching, otherwise you will not find the corresponding resources


 ServletConfig interface


When the Servlet container initializes the Servlet, it will create a ServletConfig object for this Servlet, and pass the ServletConfig object to the Servlet as a parameter.

The initialization parameter information of the current Servlet can be obtained through the ServletConfig object. A Servlet can only correspond to one ServletConfig object, that is, the initialization parameters of the Servlet are only valid for the current Servlet.

Get the ServletConfig object

1) Extract directly from the init() method with parameters

@Override
public void init(ServletConfig config) throws ServletException {
//从带参init方法中,提取ServletConfig对象
this.servletConfig = config;
}

2) Call the getServletConfig() method provided by GenericServlet to obtain

//调用 GenericServlet 提供的 getServletConfig 方法获得 ServletConfig 对象
ServletConfig servletConfig = this.getServletConfig();

Methods provided by the ServletConfig interface

String getInitParameter(String name) According to the initialization parameter name name, return the corresponding initialization parameter value.
Enumeration getInitParameterNames() Returns the enumeration collection of all initialization parameter names of the Servlet, or returns an empty collection if the Servlet has no initialization parameters.
ServletContext getServletContext() Returns a ServletContext object representing the current web application.
String getServletName() Returns the name of the servlet, which is the value of the element in web.xml.

 


Nothing is easy in the world, there are many people who want to be lazy, so there is a shortcut

Just like: There is no road in the world, if there are many people walking, it becomes a road


 ——Lungcen

 

Guess you like

Origin blog.csdn.net/qq_64552181/article/details/129762636
Recommended