How Servlets work

Source: Internet
Author: User

One: servlet definition

A servlet is a Java application that runs on the server side and is used to process client requests and respond to a program.

(The Servlet object is initialized when the servlet container is started and, when requested for the first time, is instantiated by the servlet container, which is stored in memory.)

If there are multiple requests, the servlet is no longer instantiated and is still being processed by the servlet, each of which is a thread, not a process, so the servlet has very high performance in processing the request.

for a servlet, it is designed to be multithreaded (if it is single-threaded, you can imagine that when 1000 people request a Web page at the same time, before the first person to obtain the result of the request, the other 999 people are in a depressed wait),

If a new thread object is created for each request of each user, the system will be expensive to create the thread and destroy the thread, greatly reducing the efficiency of the system.

Therefore, there is a thread pool behind the servlet multithreading mechanism, and the thread pool creates a certain number of thread objects at the beginning of initialization.

By increasing the utilization of these objects, avoid creating objects at high frequency to achieve the purpose of improving the efficiency of the program.

Two: Simple servlet instance

Import the required packages

Import javax.servlet.http.*;

Import javax.servlet.*;

Import java.io.*;

public class Firstservlet extends HttpServlet {

Methods for handling requests

public void Doget (HttpServletRequest req, HttpServletResponse resp)

Throws Servletexception, Java.io.IOException {

Data sent to client-side console mode output

System.out.println ("Hello Servlet");

Data sent to client->html page output

Resp.setcontenttype ("text/html");

Resp.getwriter (). Print ("

Resp.getwriter (). Print ("

Resp.getwriter (). Print ("

Resp.getwriter (). Print ("<body>");

Resp.getwriter (). Print ("Hello World");

Resp.getwriter (). Print ("</body>");

Resp.getwriter (). Print ("

}

}

Three: Servlet configuration to Tomcat

Tomcat is a web container, also called a Web server. We all know that there are 13 standards for the Java EE, most of which are interfaces, and Tomcat just implements the JSP and servlet development standards. All development standards are implemented, namely, application servers, such as JBoss.

The compiled servlet class can only be run in the Tomcat container, the client browser does not have direct access to the servlet and needs to be configured in Web. xml

<servlet>

<servlet-name>FirstServlet</servlet-name>

<servlet-class>FirstServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>FirstServlet</servlet-name>

<url-pattern>/servlet/FirstServlet</url-pattern>

</servlet-mapping>

After Tomcat starts successfully, enter in the browser: Http://localhost:8080/abingtest/servlet/FirstServlet

Four: The principle of servlet operation

When we enter Http://localhost:8080/abingtest/servlet/FirstServlet in the browser, how does tomcat find our servlet, run it, and return to the page we want to see?

1. WebApplication's standard directory structure:

Web-inf/classes

/lib

Xml

That is, under a complete Web application directory, you must include the above directory structure.

The Classes folder is the class file used in the project, all compiled by the JDK into a. class file

Lib folder is a jar package referenced in our project

Web. XML is the configuration document for the entire application.

With that in view, we'll look at the Tomcat workflow.

2. Tomcat parsing URL

A) First look at the information contained in the URL: "Protocol" + "port number" + "Path (project name + file path)"

After Tomcat starts, listen to our port 8080, when a URL request is sent, parse out the project name Abingtest, and then go to the WebApps directory to search for the project folder.

b) After the project file is found, start looking for the class file.

This time Tomcat goes to the Web. xml file to find the <servlet-mapping> configuration section that contains the "Servlet/firstservlet" string, and then finds the location of the class file.

3. Doget () and DoPost () methods in Servelt

The Firstservlet we wrote inherited the HttpServlet, rewritten the Doget () method in HttpServlet, and a HttpServlet () method in Dopost. Both of these methods are used to handle HTTP requests. The servlet invokes the service method automatically based on our method of submitting the form (Method=post/get) (in the next article we'll explain in detail how the service method automatically calls the Doget () method in Firstservlet)

4. How servlets receive Data

Import javax.servlet.http.*;

Import javax.servlet.*;

Import java.io.*;

public class Firstservlet extends HttpServlet {

public void doget (HttpServletRequest request, httpservletresponse response)

Throws Servletexception, Java.io.IOException {

Get form data

String userName = Request.getparameter ("UserName");

}

}

The HTTP protocol wraps all the contents of a Web page into a request object passed to the servlet, which gets all the data in the form through this object, which is returned to the client browser via the response object after processing is complete.

5. The life cycle of the servlet

The life cycle of the servlet is managed by the Tomcat container

A) The client makes a request to->web the server forward to the Web container tomcat;

b) The Tomcat main thread responds to requests forwarded to the user to create two objects: HttpServletRequest and HttpServletResponse;

c) Find the correct servlet,tomcat from the URL in the request to create or assign a thread to it, and pass 2 created two objects to the thread;

D) Tomcat invokes the Servic () method of the servlet, calling the Doget () or Dopost () method according to the different request parameters;

e) Assuming an HTTP GET request, the Doget () method generates a static page and combines it into the response object;
At the end of the servlet thread, Tomcat sends the Response object to the HTTP response back to the client, removing both the request and the response object.
From this process, we can understand the servlet's life cycle: servlet class loading (corresponding to 3 steps), servlet instantiation (corresponding to 3 steps), calling the Init method (corresponding to 3 steps), invoking the Service () method (corresponding to 4, 5 steps); calling Destroy () Method (corresponds to 6 steps).

V: Various stages of the servlet life cycle

The servlet is run in a servlet container and its lifecycle is managed by the container. The life cycle of the servlet is represented by the Init (), service (), and Destroy () methods in the Javax.servlet.Servlet interface.

The life cycle of the servlet consists of the following 4 phases:

(1) Loading and instantiation

The servlet container is responsible for loading and instantiating the servlet. The servlet instance is created when the servlet container is started, or when the container detects that the servlet is needed to respond to the first request. When the servlet container is started, it must know where the desired servlet class is, and the servlet container can load the servlet class from the local file system, the remote file system, or other network services through the class loader, and after successful loading, the container creates an instance of the servlet. Because the container is creating a servlet instance through the Java Reflection API, invoking the default constructor method of the servlet (that is, the constructor without parameters), we should not provide a constructor with parameters when writing the Servlet class.

(2) initialization

After the servlet is instantiated, the container will invoke the servlet's init () method to initialize the object. The purpose of initialization is to have the Servlet object do some initialization work before processing the client request, such as establishing a connection to the database, obtaining configuration information, and so on. For each servlet instance, the init () method is called only once. During initialization, the servlet instance can use the ServletConfig object that the container prepares for it to get initialized parameter information from the configuration information of the Web application (configured in XML). During initialization, if an error occurs, the servlet instance can throw a Servletexception exception or Unavailableexception exception to notify the container. The servletexception exception is used to indicate a generic initialization failure, such as the initialization parameter not found, and the unavailableexception exception is used to notify the container that the servlet instance is unavailable. For example, if the database server is not started and the database connection cannot be established, the servlet can throw a unavailableexception exception to the container to indicate that it is temporarily or permanently unavailable.

(3) Request processing

The servlet container invokes the servlet's service () method to process the request. It is important to note that the init () method must execute successfully before the service () method call. In the service () method, the Servlet instance obtains information about the client and request information through the ServletRequest object, and, after processing the request, invokes the method of the Servletresponse object to set the response information. During the service () method execution, if an error occurs, the servlet instance can throw a Servletexception exception or unavailableexception exception. If the unavailableexception exception indicates that the instance is permanently unavailable, the servlet container invokes the instance's destroy () method to release the instance. Any subsequent requests for that instance will receive the HTTP 404 (requested resource unavailable) response sent by the container. If the unavailableexception exception indicates that the instance is temporarily unavailable, any requests for that instance will receive a response from the container for HTTP 503 (the server is temporarily busy, unable to process the request) during the temporarily unavailable time period.

(4) Termination of service

When the container detects that a servlet instance should be removed from the service, the container invokes the instance's destroy () method so that the instance can free the resources it uses and save the data to the persistent storage device. When the memory needs to be freed or the container is closed, the container invokes the Destroy () method of the servlet instance. After the Destroy () method call, the container releases the servlet instance, which is then reclaimed by the Java garbage collector. If the servlet is required to process the request again, the servlet container creates a new servlet instance.

During the lifetime of the servlet, the creation of the servlet instance, the init (), and Destroy () methods of the calling instance are done only once, and when the initialization is complete, the servlet container saves the instance in memory by invoking its service () method, Service for the received request. The UML sequence diagram for the entire life cycle of the servlet is given below

How Servlets work

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.