How servlet works

Source: Internet
Author: User

The servlet runs in the servlet container. The container is responsible for finding and creating servlet instances and calling a group of servlet methods according to servlet specifications. These methods are also called Life Cycle methods. The specific call process is shown in:

Detailed description of servlet Lifecycle

As shown in, the servlet lifecycle can be divided into four stages: loading class and instance creation stage, initialization stage, service stage, and instance Destruction stage. The following describes the programming tasks and precautions of each stage in detail.

(1) loading class and instance Creation

When a client sends a request to the Web server, the protocol and path of the request must comply with the following format:
Http: // serverip: Port/Application-path/resource-Path

Specifically, serverip is the IP address of the web server, or a domain name, such as 192.168.0.1, 202.196.152.115,
Localhost, www.sina.com.cn, etc. Port is the service port of the Web server. If it is port 80, you can leave it empty.
Application-path is the path of an application released on the server. If it is the default application (such as Tomcat root), it can be
Null. Resource-path is the resource path of the server to be accessed by the client. For example:
Http: // localhost: 8080/Serv-APP/login.html indicates to access the resources corresponding to/login.html in the path Serv-app on the local machine through port 8080.
Http: // localhost: 8080/Serv-APP/basic/time indicates that the resources corresponding to/basic/time in the application whose path is Serv-app on the local machine are accessed through port 8080.

How does the Web server explain the Request Path and send resources to the client? In the previous section "create and publish a web application", we said that the web server will map the Application Path/Serv-app to a specific directory structure on the disk, in this example, it is the Serv-app in the webapps directory of the Tomcat server. /Login.html and/basic/time are the resource paths of the application. The path is the "virtual" path like the Application Path, the server maps it to a specific file or program of the system. The specific process is shown in:

 

Javaee web specification specifies the server search servlet class path for the application directory structure in the WEB-INF/classes directory and all jar files under the WEB-INF/lib. Therefore, you need to put the timeservlet in the WEB-INF/classes according to the following directory structure:
WEB-INF/classes/COM/allanlxf/servlet/basic/timeservlet. Class

The servlet deployment is described as follows:

<Servlet>
<Servlet-Name> timeservlet </servlet-Name>
<Servlet-class>Com. allanlxf. servlet. Basic. timeservlet</Servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> timeservlet </servlet-Name>
<URL-pattern>/Basic/Time</Url-pattern>
</Servlet-mapping>

I.When to create a ServletInstance?

By default, the servlet instance is created when the first request arrives and reused later. If some servlets require complex operations, such as opening files and initializing network connections, you can notify the server to create the servlet instance at startup. 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>

The value marked by <load-on-startup> must be a numerical value, indicating the servlet loading sequence. The values and meanings are as follows:
Positive or zero: The servlet must be loaded when the application starts. The container must ensure that the servlet with a small value is loaded first. If multiple
The <load-on-startup> values of servlets are the same. The Container determines the loading sequence.
Negative number or unspecified <load-on-startup>: The container determines the loading time, usually when the first request arrives.

(2) initialization

Once a servlet instance is created, the web server automatically calls the init (servletconfig config) method to initialize the servlet. The method parameter config contains the servlet configuration information, such as the initialization parameter, which is created by the server.

I.How to configure Servlet?

In web. XML, the servlet definition tag, 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> allanlxf </param-value>
</Init-param>
<Init-param>
<Param-Name> blog </param-Name>
<Param-value> http://allanlxf.blog.sohu.com </param-value>
</Init-param>
</Servlet>

Two initialization parameters "user" and "blog" are configured with their values allanlxf and http://allanlxf.blog.sohu.com, so that you do not need to modify the servlet code to modify the user name and blog address, you just need to modify the configuration file.

II.How to read Servlet?

The following methods are defined in servletconfig to read initialization parameter information:

Public String getinitparameter (string name)

Parameter: name of the initialization parameter.
Return Value: the value of the initialization parameter. If not configured, null is returned.

For example, getinitparameter ("user") returns allanlxf
Getinitparameter ("blog") returns http://allanlxf.blog.sohu.com

Public java. util. Enumeration getinitparameternames ()

Return: enumeration of all initialization parameter names configured by the servlet.

III.Init (servletconfig)Number of method executions

In the servlet lifecycle, this method is executed once.

IV.Init (servletconfig)Methods and threads

This method is executed in a single-threaded environment, so developers do not need to consider thread security issues.

V.Init (servletconfig)Methods and exceptions

This method can throw servletexception during execution to notify the Web server of failed servlet instance initialization. Once servletexception is thrown, the web server does not send client requests to the servlet instance for processing, but reports initialization failure exception information to the client. The servlet instance will be destroyed from the memory. If a new request is sent, the web server creates a new servlet instance and initializes the new instance.

VI.Configure initialization parametersOverride Init (servletconfig)Method

Configuring initialization parameters is not necessarily related to overwriting the init (servletconfig) method, which is easy for beginners to confuse. The purpose of configuring initialization parameters is to compile a "general" servlet, that is, to change the servlet function by changing the value of the initialization parameter, without modifying the source code of the servlet. The reason for overwriting the init (servletconfig) method is that some servlets need to perform one-time operations to provide services to customers, such as applying for resources, opening files, and establishing network connections. These operations are either time-consuming, or these resources are necessary to provide services.

(3) Service

Once the servlet instance is successfully created and initialized, the servlet instance can be used by the server to serve client requests and generate responses. In the service phase, the web server calls the Service (servletrequest request, servletresponse response) method of the instance. The request object and response object are created by the server and transmitted to the servlet instance. The request object encapsulates the information sent from the client to the server, and the response object encapsulates the information sent from the server to the client.

I.Service ()Responsibilities

The Service () method is the core method of servlet. the client's business logic should be executed in this method. The development process of a typical service method is as follows:

Parse client request-> execute business logic-> OUTPUT response page to client

II.Service ()Methods and threads

To improve efficiency, the servlet specification requires that a servlet instance must be able to serve multiple client requests at the same time, that is, the Service () method runs in a multi-threaded environment, servlet developers must ensure the thread security of this method.

III.Service ()Methods and exceptions

The Service () method can throw servletexception and ioexception during execution. Servletexception can be thrown during the process of processing client requests, such as resource unavailability and database unavailability. Once this exception is thrown, the container must recycle the request object and report the exception information on the client. Ioexception indicates an input/output error. programmers do not have to worry about this exception and report it directly to the client by the container.

IV.Write thread-Safe Resources

Because the Service () method of the servlet instance runs in a multi-threaded environment at the same time, the factors that must be considered when writing the servlet are thread security issues, this is also the most error-prone part of servlet compilation. The relationship between servlet methods, threads, and programming principles are described in detail.

Notes for programming:

1) when the server thread executes the init () method of the servlet instance, all client service thread threads cannot execute the Service () method of the instance, no thread can execute the destroy () method of the instance. Therefore, the init () method of servlet works in a single-threaded environment, so developers do not have to consider any thread security issues.

2) When the server receives multiple requests from the client, the server will execute the Service () method of the servlet instance in the separate client service thread to serve each client. At this time, multiple threads will execute the Service () method of the same servlet instance at the same time. Therefore, thread security must be considered.

3) Please note that although the Service () method runs in a multi-threaded environment, it is not necessary to synchronize this method. It depends on the resource type accessed during the execution of this method and the access method to the resource. The analysis is as follows:

I. if the service () method does not access servlet member variables or global resources such as static variables, files, and database connections, it only uses the resources of the current thread, for example, temporary variables, request and response objects that do not point to global resources. This method is thread-safe and does not require any synchronization control.

Ii. if the service () method accesses the servlet member variable but the operation on the variable is read-only, the method itself is thread-safe and does not require any synchronization control.

Iii. if the service () method accesses the servlet member variables and the operations on the variables are both read and write, a synchronization control statement is usually required.

IV. if the service () method accesses the Global static variable, if there may be other threads in the system to access the static variable at the same time, if there are both read and write operations, A synchronization control statement is usually required.

V. if the service () method accesses global resources, such as files and database connections, a synchronous control statement is usually required.

V.About singlethreadmodel

By default, the web server creates a servlet for each <servlet> label declared servlet in Web. xml.The only oneThe instance will be handed over to multiple threads to process concurrent client requests. Therefore, Servlet developers must ensure the servlet thread security.

The servlet specification also specifies a singlethreadmodel interface, which is a flag interface and has no way to tell the container how this type of servlet works. As long as the servlet class implements this interface, the web server must ensure that the servlet instance of this type can only serve one request at a time, that is, the Service () method is not in the concurrent thread.

Note: This running mode only ensures that the member attributes of the servlet instance work in a single-threaded environment, but other resources accessed by the servlet, for example, httpsession, file, network connection, and so on may be accessed by other servlet instances at the same time. Therefore, this running mode cannot completely solve the thread concurrency problem. Developers are advised to use it with caution.

(4) Destruction

When the Web server deems that the servlet instance does not exist, such as application reload, server shutdown, and Servlet has not been accessed for a long time. The server can destroy (or detach) the instance from the memory. The Web server must ensure that the destroy () method of the instance is called before the servlet instance is detached, so that the resources requested by the servlet can be recycled or other important processes can be performed.

I.Destroy ()And Service ()
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 calling the destroy () method. Once the destroy () method has been executed, the web server rejects all new requests to the servlet instance, and the destroy () method exits, the servlet instance can be recycled.

Lifecycle application instance

Compile a servlet that records the IP addresses of all clients that have accessed the instance since the instance was created to a log file on the server. The path of the log file must be specified by the deployer when the servlet is deployed.

Code: 

PackageCom. allanlxf. servlet. lifecycle;

ImportJavax. servlet .*;
ImportJavax. servlet. http .*;
ImportJava. Io .*;

/**
* The servelt operating principle instance records all IP addresses that have accessed the client to a file on the server.
*
*@ AuthorAllanlxf
*@ Version1.0
*/
Public ClassIplogservletExtendsHttpservlet
{
PrivatePrintwriter logger;

/**
* Servlet initialization method. File paths on different platforms are written differently.
* The file path used to save the Client IP address is provided in the form of initialization parameters, So that you only need to deploy the Servlet
* Specify or change the path of the file, instead of re-compiling the Servlet Source code.
* Because the efficiency of frequently opening and closing files is very low, open the file in the init () method and write the file in the Service () method.
*, Closing the file in the destroy () method is the best practice.
*@ ThrowsServletexception
* If the servlet does not configure the file specified by the initialization parameter filename or filename, the file cannot be found.
*/
Public VoidInit ()ThrowsServletexception
{
String filename = getinitparameter ("FILENAME ");
Try
{
Fileoutputstream fout =NewFileoutputstream (filename,True);
Logger =NewPrintwriter (fout );
}Catch(Ioexception E)
{
Throw NewServletexception ("fail to open:" + filename );
}
}

/**
* Servlet service method, which records the IP address of the client to the log file.
* Because a file is a shared resource and multiple threads write a file at the same time, the results may be messy. Therefore, you must control synchronization.
* Access.
*@ ParamThe object where the request contains the client request information.
*@ ParamResponse: The object that contains the server response information.
*/
Public VoidService (httpservletrequest request, httpservletresponse response)
ThrowsServletexception, ioexception
{
Response. setcontenttype ("text/html; charset = GBK ");
Printwriter out = response. getwriter ();
Out. println ("<HTML> ");
Out. println ("Out. println ("<title> ip-log </title> ");
Out. println ("Out. println ("<body> ");
Out. println ("<H3 align = \" center \ "> thanks for your visiting! </H3> ");
Out. println ("</body> ");
Out. println ("// Record log information

Synchronized(This)
{
Logger. Print (NewJava. util. Date ());
Logger. Print (": From Client :");
Logger. println (request. getremoteaddr ());
}
}

/**
* Servlet instance Destruction method. Disable log files.
*/
Public VoidDestroy ()
{
Logger. Close ();
}
}

Servlet and URL matching

To allow the client to access the servlet in the server, the deployer must configure an access path for each servlet. The path can be written in the following three ways:

(1) exact Path Matching
Start with "/", followed by a specific path name. It can also contain sub-paths. For example,/time,/basic/Time, And/basic/time/HTTP all belong to exact path matching. In this matching mode, the client can only access the servlet instance through this unique path.

(2) fuzzy Path Matching
Start with "/" and end with "/*". Sub-paths can be included in the middle. For example,/*,/basic/*, And/user/management/* all belong to fuzzy Path Matching. In this matching mode, the client can access the servlet instance through a set of related paths, that is, the additional information can be transmitted through the URL.

(3) Extension matching
Start with "*." and end with any other character. For example, *. Do, *. Action, and *. CTRL all belong to the extension matching. In this matching mode, the client can access the servlet instance through a set of related paths, that is, the additional information can be transmitted through the URL.

(4) default servlet
The servlet configured as "/" is the default servlet of the application. The web server will send all unidentifiable client requests to the default servlet for processing.

Matching priority

Multiple servlets are published in a web application at the same time. It is inevitable that multiple servlets can serve a single request. For example, three servlets are released in the system, and their matching paths are:/* and :/*,*. do and/basic. If the client's request path is/basic,/basic and/* can both serve the request. Therefore, the specification specifies the sequence rules for the Web server to match the servlet. The specific sequence rules are as follows:

1. Find the servlet with the exact path matching.

2. If there is no exact path match, follow the fuzzy path match. If multiple paths exist, take the servlet with the longest fixed part of the path.

3. Search for matching extensions.

4. If none of the above rules match the servlet, the system will send the request to the default servlet for processing.

5. If no default servlet exists, report the error message to the caller.

Assume that the system has the following servlet matching mode:

The following shows how to access the application in different paths. The matching results are as follows:

How servlet works (transfer)

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.