[Switch] Servlet execution process and life cycle of JavaWeb

https://www.cnblogs.com/vmax-tam/p/4122105.html

Servlet concept

What is a servlet?

  There is an interface called Servlet in Java. If an ordinary class implements this interface, this class is a Servlet. There is an implementation class called HttpServlet under Servlet. If an ordinary java inherits the HttpServlet class and overrides its doGet and doPost methods, then this ordinary class can also be called Servlet. Finally, the servlet program is handed over to the server to run!

  So, when we write a servlet and hand it over to the server, how does it execute! ?

Servlet execution process

We wrote a servlet named hello. So how does the browser access this resource?

To say this, let's first learn about the browser's address input.

  There is an input like this: http://localhost:8080/day10/hello

http: http protocol

localhost: Domain name, go to the hosts file under the local C drive to check whether there is an IP mapping record address corresponding to the domain name. If there is, go to the IP directly, if not, go to DNS to find it.

8080 port number, here refers to the tomcat server. localhost matches the default site of tomcat, go to the webapps directory to find the web application.

/day10 The name of the web application. Find whether there is a directory of day10 under webapps.

/hello web resource. Look for this resource under the day10web application. (If you don't understand it, it's best to first understand the file structure in tomcat.)

 

    The /hello resource here is a servlet we wrote. After the server gets this string, it goes through the following process to find the servlet!

        -> get /hello string

 

        -> Use /hello to find the content in the <url-pattern> tag under each <servlet-mapping> in the web.xml file, and then get the sevlet-name

 

        -> Use sevlet-name to find the corresponding servlet configuration with the same name in the servlet tag.

 

        -> Get the servlet-class content in the servlet configuration. String: gz.itcast.a_servlet.HelloServlet

 

copy code
<servlet>
    <servlet-name>HelloServlet</servlet-name> 
  <servlet-class>com.vmaxtam.numzero.addServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>HelloServlet</servlet-name>
   <url-pattern>/hello</url-pattern>
</servlet-mapping>
copy code

 

    Finally, the HelloServlet object is instantiated through reflection, and then the methods in HelloServlet are called.

 

 

Servlet mapping path

 

<url-pattern>/hello</url-pattern> The mapping path here can also be filled in in many ways!

                url-pattern browser input URL

Exact match /demo1 http://localhost:8080/day10/demo1

                 /itcast/demo1          http://localhost:8080/day10/itcast/demo1  

 

fuzzy matching

                   /* http://localhost:8080/day10/any path

                  /itcast/* http://localhost:8080/day10/itcast/any path

                  *. Suffix http://localhost:8080/day10/any path. Suffix. For example *.do, *.action, *.html

 

Notice: 

1) The url-pattern should start with / or *. This way of writing demo1 is wrong! !

2) It is illegal to write /itcast/*.do. You cannot use both fuzzy matches at the same time

3) When multiple servlets are matched for a request:

a) The longest and most similar url-pattern will be matched first

b) The url-pattern ending with the suffix has the lowest priority! ! !

 

Speaking of this, someone asked: This is just looking for Servlet files, so if you are looking for static files (html, xml, etc.) of the server, what is the execution process of the server? ? What if the file you are looking for doesn't exist?

Here is the explanation for you:

 

 

default path

 

There is a default Servlet in the tomcat server, called DefaultServlet, and the url-pattern of DefaultServlet is / . The role of this DefaultServlet is mainly used to process requests for static resources.

 

    Enter: http://localhost:8080/day10/test.html How to find the resource?

 

        1) Find the web.xml file under the web application of day10, use /test.html, if there is a match to see if there is a url-pattern that matches the rule, if found, the corresponding dynamic resource (servlet) will be executed.

 

        2) If the corresponding url-pattern cannot be found, go to the root directory of the current web application on day10 to find a static resource file with the name test.html. If this file is found, DefaultServlet reads the content of the static file and outputs it to the browser client.

 

        3) If the static resource file of test.html cannot be found under day10, then a 404 page is returned.

 

I only mentioned how the server finds the servlet file, so how does the servlet execute! ! ! That's the point, the life cycle of a servlet

 

Servlet life cycle

When does the tomcat server create the servlet object? When are objects destroyed? What method is called when? !

In fact, it is such a process:   

      1. Creation of the Servlet object.

      2. The Servlet object executes certain methods to serve us.

      3. Destruction of the Servlet object.

 

And this process has 4 very core methods that need to be executed:

Constructor: Called when the servlet object is created. By default, the servlet object is created when the servlet is accessed for the first time. Only called once. servlet is single instance in tomcat server.

init method: Called after the servlet object is created. Used to initialize the servlet object. Only called 1 time.

service method: called every time a request is made. Called n times.

destroy method: Called when the tomcat server is stopped or the web application is reloaded. Only called 1 time.

 

Let's use pseudo code to demonstrate the execution process of Servlet in the whole process from the browser sending the request to the server making the corresponding response!

Browser input: http://localhost:8080/day10/hello

 Enter web.html to query resources.

get string gz.itcast.a_servlet.HelloServlet

 

Simulate the running code inside the tomcat server:

1) Construct the HelloServlet object with reflection

  1.1 Get the bytecode object

    Class clazz = Class.forName("gz.itcast.a_servlet.HelloServlet ")

  1.2 Call the parameterless constructor to construct an object

    Object obj = clazz.newInstance(); ----1.Servlet's constructor is executed

2) Create a ServletConfig object and call the init method

     2.1 Get the init method object

    Method method = clazz.getDeclareMethod("init",ServletConfig.class);

  2.2 Execute the init method

    method.invoke(obj, config); --2. Servlet's init method is executed

 

3) Create request and response objects and call the service method

  3.1 Get the service method object

    Method m = clazz.getDeclareMethod("service",HttpServletRequest.class,HttpServletResponse.class);

  3.2 Execution method

    m.invoke(obj,request,response); --3.Servlet's service method is executed

 

4) When the tomcat server stops or the web application is reloaded, the destroy method is called

  4.1 Get the destroy method object

    Method method = clazz.getDeclareMethod("destroy",null);

   4.2 Execution method

    method.invoke(obj,null); --4.Servlet's destroy method is executed

 

If the text is not intuitive enough, then I can look at the flow chart

Servlet object autoloading

introduce

    By default, the servlet object is created the first time the servlet is requested. Call the init method after creation. If the construction method or the init method executes a lot of business logic, the user's waiting time when accessing the servlet for the first time will become longer, which will affect the user's experience.

Solution

    Change the timing of servlet creation: let the servlet object be created when the tomcat server starts the web application loading.

 

In the servlet configuration, add a configuration:

<load-on-startup>正整数</load-on-startup>

 

<servlet>

    <servlet-name>LifeDemo1</servlet-name>

    <servlet-class>gz.itcast.c_life.LifeDemo1</servlet-class>

    <load-on-startup>1</load-on-startup>

  </servlet>

Note: The larger the value of the positive integer, the lower the priority of creation! !

 

 Servlet multi-thread safety problem

    Conclusion: servlet is single instance multithreaded in tomcat server.

 

Multithreading concurrency problem

  Shared data is manipulated between multiple threads at the same time! ! !

Solve multi-threaded concurrency problems

  Add a unique object lock to the code block that needs to be synchronized.

 

How to write thread safe servlet class:

  1) Try not to use member variables.

  2) If you use member variables, add a lock to the code block that uses the member variables. Minimize the scope of synchronized code blocks to avoid performance problems due to synchronization.

 

Init method

  A parameterless init method is provided in GenericServlet! ! !

    Init with parameters: This method is one of the four life cycle methods of Servlet, which must be called by the server. In this method, the parameterless init method is called.

    Parameterless init: This method is designed by Sun to facilitate developers to rewrite. In this method, the initialization of the servlet object is implemented. This method will be called by the parameterized init method!

 

Learning makes you want to sleep because that's where the dream begins.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325300542&siteId=291194637