Jsp/servlet Working principle

Source: Internet
Author: User
Tags html header

Jsp/servlet working principle (reprint) 2014-03-08 23:20 1829 People Read review (0) Favorite report Servlet

The Servlet does not have the main method, can not run independently, it needs the support of the container, Tomcat is the most common Jsp/servlet container.

The servlet runs in the servlet container, and the container manages the entire process from creation to destruction.

For a user to reach the servlet request, the servlet container creates the ServletRequest object and the Servletresponse object that are specific to the request, and then invokes the Servlet's service method. The service method obtains the customer request information from the ServletRequest object, processes the request, and returns the response information to the customer through the Servletresponse object.

The life cycle of the Servlet

Start by introducing Wikipedia content:

1. When the servlet is deployed in the application server (the part of the application server that manages the Java components is abstracted as a container), the container controls the servlet's life cycle.

2. Unless specially formulated, the servlet will not be loaded when the container is started, and the servlet will only be loaded and instantiated on the first request.

3. Once the servlet is loaded, it is generally not removed from the container until the application server shuts down or restarts. However, the servlet may be deleted when the container does a memory recovery action. It is for this reason that the first time it takes to access a servlet is much greater than the time it takes to access it later.

1. servlet running in Server: 1. Load->2. Initialize-> 3. Call-4. Destroy

2. Life cycle: The life cycle of a servlet begins its life cycle after "2. Initialize" and ends its life cycle after "4. Destroy"

3 . In general, a servlet instance corresponds to a request that the servlet instance can handle for multiple user requests.

-----------------------------

After Google found, many people are arguing whether the servlet is a singleton mode. The two Web pages given here can be seen as follows:

1. servlet is not a singleton. However, in general, there is only one instance of a servlet.

2, because servlet/jsp is executed in multithreaded mode by default, the security of multithreading needs to be considered very carefully when writing code. Here refer to the blog servlet single-instance multithreading mode and Baidu Encyclopedia.

The instance procedure for a servlet is generally as follows:

There are four things to do when the server receives a client request.

(1) Loading and instantiation

If the servlet container has not instantiated a Servlet object yet, the container loads and instantiates a servlet. Creates an instance of the Servlet class. If a Servlet object already exists, no new instances are created at this time.

(2) initialization
After the servlet instance is generated, the container is responsible for invoking the Init () method of the servlet instance to do some additional initialization before processing the user request.
(3) Processing requests
When the servlet container receives a servlet request, it runs the service () method of the corresponding servlet instance, and the service () method calls the corresponding Doget or Dopost method according to the user's request to process the user request. And then into the corresponding method to invoke the logical layer of the method to achieve response to the customer.
(4) Destruction
When the servlet container decides to remove a servlet from the server (such as a servlet file being updated), it invokes the Destroy () method of the servlet instance and does some other work before destroying the servlet instance.

where (1) (2) (4) is executed only once throughout the Servlet's life cycle.

0. If the servlet is configured with Load-on-startup in Web. XML, the servlet is initialized in the container load.

    1. <servlet>
    2. <servlet-name>AAA</servlet-name>
    3. <servlet-class>servlet. Aaa</servlet-class>
    4. <load-on-startup>1</load-on-startup>
    5. </servlet>
<servlet>            <servlet-name>AAA</servlet-name>            <servlet-class>servlet. Aaa</servlet-class>            <load-on-startup>1</load-on-startup></servlet>

1, the general servlet only one instance after boot (only one mapping for the same servlet), if a servlet has more than one mapping, there will be more than one servlet instance.

2. In the Web. xml file, some servlets have only <serlvet> elements, there are no <servlet-mapping> elements, so that we cannot access these servlets by URL, and this servlet usually The <servlet> element configures a <load-on-startup> child element to allow the container to automatically load these servlets at startup and invoke the Init () method to accomplish some global initialization. that is, if you want to load some servlets through a URL, you need to write the <servlet-mapping> element. If the servlet is run when the container is loaded, the write <servlet-mapping> element is not required.

3. When there is only one instance of the servlet, when there are multiple client accesses, the service method that has been instantiated is called several times to process the request. Sometimes a container generates a Servlet object instance based on a client request or generates multiple Servlet object instances and joins them into the servlet instance pool to process the request, referring to the discussion

How the Servlet works

Combined with the flowchart given on the right:

When the client browser requests a servlet from the server, the server receives the request and first retrieves to the container whether the servlet instance that matches the request already exists.

If it does not exist, the servlet container is responsible for loading and instantiating an instance object of that servlet, and then the container framework is responsible for invoking the instance's Init () method to do some initialization work on the instance, and then the servlet container runs the service () method of the instance.

--If the Servlet instance already exists, the container framework invokes the service () method of the instance directly.
At run time, the service () method automatically dispatches the Doxx () method that corresponds to the user request to respond to a user-initiated request.

Typically, there is only one instance of each Servlet class in the container, and whenever a request arrives, a thread is assigned to process the request.

When processing a request:

1. The servlet container creates a request object servletrequst that encapsulates the information requested by the user in order to process the client request, and also creates a response object, Servletresponse, that responds to the client request and wants the client to return the data.

2. The servlet container then passes the created Servletrequst and Servletresponse objects to the servlet requested by the user.

3. The servlet uses the data contained in Servletresponse and its own business logic to process the request, and writes the processed results in Servletresponse, and finally the servlet container passes the response to the user.

Use of Servlets

1, custom servlet generally need to inherit httpservlet, and HttpServlet is inherit Genericservlet, and Genericservlet is inherit servlet.

Cause: HttpServlet is a class that is specific to the HTTP protocol, and the servlet interface and Genericservlet are not specific to any protocol. The Servlet interface defines five methods, of which the more important three methods involve the life cycle of the servlet, respectively, the Init (), service (), and Destroy () methods mentioned above. Genericservlet is a generic, non-protocol-specific servlet that implements the Servlet interface. And HttpServlet inherits from Genericservlet, so HttpServlet also implements the Servlet interface. So we only need to inherit httpservlet when we define the servlet. The service () method is implemented in HttpServlet, and the request Servletrequest,servletresponse is strongly converted to HttpRequest and HttpResponse.

2. The actual handler for the request is the Doget,dopost method, and the custom servlet class needs to override the Doget,dopost method.

The Doget,dopost method in the base class HttpServlet is not implemented specifically, only some exception handling is given, and the error message is returned. So the specific processing code we need to write ourselves.

3. What operations need to be handled in the Doget method, what operations need to be handled in the Doput method?

Get Request: The Doget method is called when a request or form is sent directly in the address bar of the browser to the address that is being sent, without indicating that the post form is sent (table Tammer considers the Get commit).

1) because the Get-mode request converts the name and value of the request parameter to a string and is appended to the original URL, you can see the name and value of the request parameter on the address bar, which is less secure.

2) The GET request has a smaller amount of data.

3) Only strings can be passed, binary data cannot be passed

4) The server randomly accepts the Get method data, once the power outage and so on, the server also does not know whether the information is sent complete

Post Mode request: The form is sent as post.

1) The Post method sends the request parameter and the corresponding value in the HTML header transmits, the security is relatively high.

2) post delivers a large amount of data, which is generally considered to be unrestricted, but often depends on server-side limitations.

3) There is no limit to the type of data passed and the binary data can be passed

4) Moreover, when the Post method accepts data, the server first accepts the data information, and then accepts the data, using post, the server can know whether the data is complete.

Comparison: Figure from HTTP Method: GET vs. POST

Commonly used methods of use:

You typically use the Dopost method, and then Doget method calls Dopost method to

Here is an explanation of the servlets:doget and dopost in stack overflow, and the example code it gives

Figure 3 ...

How JSP Works

Combined with the flowchart given on the right:

When the client browser requests a JSP page from the server, the server receives the request, first checking whether the requested JSP file content (code) has been updated, or whether the JSP file was first accessed after it was created:

-If so, the JSP file will be converted into a Servlet class Java source code file by the server-side JSP engine. Immediately after that, the Servlet class is compiled into a bytecode file, and loaded into the JVM interpretation execution, under the influence of the Java compiler. The rest is equivalent to the Servlet process.

-If the requested JSP file content (code) has not been modified, then its processing process is equivalent to a Servlet processing. The corresponding Servlet instance is retrieved directly from the server for processing.

It is important to note that the JSP file is not converted to a Servlet class when the server is started. Instead, the conversion occurs when the client accesses it (such as the JSP file content is not updated and so on, the Servlet conversion is no longer possible).
In the case of Tomcat, open the directory%tomcat%/work/% your project directory%, and then you will see there are 3 subdirectories: org/apache/jsp, if not the 3 directory, the project JSP file has not been accessed, open into the JSP directory, will see some *_jsp.java and *_jsp.class files, that is, the JSP file is converted to
The source and bytecode files of the Servlet class.
If you are interested, you can use the browser to access the JSP in the server, and then observe the JSP conversion Servlet and compile time.

Servlets and JSPs

The JSP essence is a Servlet, and its operation also requires container support.
Java and HTML code can be written in both JSP and Servlet files, unlike
Although the Servlet can also dynamically generate page content, it is more inclined to control logic.
The JSP is eventually converted into a Servlet to interpret execution in the JVM, although it can also write Java code in the JSP, but it is more biased towards the presentation of the page view.

In the MVC architecture pattern, in the case of JSPs and Servlets, C is typically used by servlets, and V is typically used by JSPs as a function.

Jsp/servlet Working principle

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.