Servlet execution process and life cycle

Source: Internet
Author: User

First, the servlet execution process:

Second, life cycle:

The life cycle of a servlet can be divided into four phases: the load class and the Create instance phase, the initialization phase, the service phase, and the instance destruction phase .

1. Initialize phase call init () method

2, in response to customer request phase. Call the Service () method, which is chosen by the service () method to execute the doget () or Dopost () method according to the submitted mode

3. Call the Destroy () method in the termination phase

1. Create a servlet instance:

By default, the servlet instance is created at the time the first request arrives and is reused later. If a servlet requires complex operations to be completed when the load is initialized, such as opening a file, initializing a network connection, and so on, you can tell the server to create an instance of the servlet when it is started. The specific configuration is as follows:

<servlet>
<servlet-name>TimeServlet</servlet-name>
<servlet-class>com.allanlxf.servlet.basic.TimeServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

To create a related class structure for a Servlet object:

2. Initialization

Once the servlet instance is created, the Web server automatically calls the init (ServletConfig config) method to initialize the servlet. The method parameter config contains configuration information for the servlet, such as initialization parameters, which are created by the server.

I. how do I configure the initialization parameters of a servlet?

In the definition tag of the servlet in Web. XML, for example:

<servlet>
<servlet-name>TimeServlet</servlet-name>
<servlet-class>com.allanlxf.servlet.basic.TimeServlet</servlet-class>
<init-param>
<param-name>user</param-name>
<param-value>username</param-value>
</init-param>
<init-param>
<param-name>blog</param-name>
<param-value>http://... </param-value>
</init-param>
</servlet>

Two initialization parameters were configured user and blog their values are username and http://. So that you do not need to modify the servlet code to modify the user name and blog address later, just modify the configuration file.

II. How do I read the initialization parameters of a servlet?

The following method is defined in ServletConfig to read the initialization parameter information:

public string Getinitparameter (string name)

Parameter: The name of the initialization parameter.
Returns: The value of the initialization parameter, if not configured, returns NULL.

Iii.init (servletconfig) method execution times

This method executes once in the servlet's life cycle.

Iv.init (ServletConfig) method and thread

The method executes in a single-threaded environment, so developers do not have to worry about thread-safety issues.

V.init (ServletConfig) methods and exceptions

This method can throw servletexception during execution to notify the Web server that the servlet instance failed to initialize. Once Servletexception is thrown, the Web server does not hand the client request to the servlet instance for processing, but instead reports the initialization failure exception information to the client, which is destroyed from memory. If a new request is being made, the Web server creates a new servlet instance and performs the initialization of the new instance

3. Service

Once the servlet instance is successfully created and initialized, the servlet instance can be used by the server to serve the client's request and generate a response. In the service phase, the Web server invokes the service of the instance (ServletRequest request, Servletresponse response) method, The request object and the response object have a server created and passed to the servlet instance. The request object encapsulates the information that the client sends to the server side, and the response object encapsulates the information that the server sends to the client.

I. Responsibilities of the service () method

The service () method is the core approach of the servlet, where the business logic of the client should be executed within the method, and the typical development process for the service method is:

Parse client request-〉 Execute business logic-〉 Output Response page to client

Ii.service () method and thread

To improve efficiency, the servlet specification requires that a servlet instance must be able to serve multiple client requests simultaneously, that is, the service () method runs in a multithreaded environment, and the servlet developer must ensure the thread security of the method.

Iii.service () method and exception

The service () method can throw servletexception and ioexception during execution. Where servletexception can be thrown during processing of client requests, such as the requested resource is not available, the database is unavailable, and so on. Once the exception is thrown, the container must reclaim the request object and report the exception information to the client. IOException represents an error in the input and output, and the programmer does not have to care about the exception, which is reported to the client directly by the container.

Instructions for programming Considerations:

1) When the server thread thread executes the init () method of the Servlet instance, all client service thread threads cannot execute the service () method of the instance, and no thread can execute the instance's destroy () method. So the servlet init () method works in a single-threaded environment, and developers don't have to worry about any thread-safety issues.

2) When the server receives multiple requests from the client, the server executes the service () method of the servlet instance in a separate client service thread thread to serve each of the clients. There will be multiple threads executing the service () method of the same servlet instance at the same time, so thread-safe issues must be considered.

3) Please note that although the service () method runs in a multithreaded environment, it is not always important to synchronize the method. It depends on the type of resource that the method accesses during execution and how the resource is accessed. The analysis is as follows:

I. If the service () method does not access the servlet's member variables and does not have access to global resources such as static variables, files, database connections, etc., it uses only the current thread's own resources, such as temporary variables that do not point to global resources, request and response objects, and so on. The method itself is thread-safe and does not have to do any synchronization control.

II. If the service () method accesses a member variable of the servlet, but the operation of the variable is read-only, the method itself is thread-safe and does not have to be synchronized.

III. If the service () method accesses the member variable of the servlet, and the operation of the variable is both read and write, it is often necessary to add a synchronization control statement.

Iv. if the service () method accesses a global static variable, it is often necessary to add synchronous control statements If there are other threads in the system that can access the static variable at the same time, if there are read and write operations.

V. If the service () method accesses global resources, such as files, database connections, and so on, it is often necessary to add synchronization control statements.

4. Destruction

When the Web server considers that the servlet instance does not exist, such as application reloading, or server shutdown, and the servlet has not been accessed for a long time. The server can destroy (also called unload) the instance from memory. The Web server must ensure that the destroy () method of the instance is called before uninstalling the servlet instance in order to reclaim the resources requested by the servlet or perform other important processing.

The Web server must ensure that all threads running in the service () method of the instance exit or wait for a period of time before the Destroy () method is called. Once the Destroy () method has been executed, the Web server rejects all new incoming requests for the servlet instance, and the Destroy () method exits and the servlet instance can be garbage collected.

Iv. servlet Parsing client HTTP request Flowchart:

1. The Web client makes an HTTP request to the servlet container;

2. The servlet container resolves the HTTP request for the Web.

3. The servlet container creates an HttpRequest object that encapsulates the HTTP request information;

4. The servlet container creates a HttpResponse object;

5. servlet container (if the servlet accessed is not created at server startup, first create a servlet instance and call the Init () method initialization object) to invoke the service () method of HttpServlet. The HttpRequest and HttpResponse objects are passed to the HttpServlet object as the parameters of the service method;

6. HttpServlet calls the HttpRequest method, obtains the HTTP request information;

7. HttpServlet calls the HttpResponse method to generate the response data;

8. The servlet container passes the results of the HttpServlet response to the Web client.

Three, Tomcat Mount Servlet three ways:

1, Serlvet container start automatically loaded some servlet, implement it only need in the Web. xml file <servlet> add <load-on-startup> 1</load-on-startup> between </servlet>, the smaller the number, the greater the priority.

2. When the servlet container starts, the customer first sends a request to the servlet

3.after the servlet class file is updated, remount the servlet




Servlet execution process and life cycle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.