"Original" https://www.toutiao.com/i6594316694657696264/
Parsing the Java servlet work process
About Servlet
- The servlet is a technology that Sun offers to develop dynamic Web resources.
- In its API, Sun provides a servlet interface that users want to use to send a dynamic Web resource (that is, to develop a Java program to output data to a browser), the following 2 steps need to be completed:
- Write a Java class to implement the Servlet interface.
- Deploy the well-developed Java class to the Web server.
The servlet's running process
- The servlet program is called by the Web server after the Web server receives a servlet access request from the client:
- The ①web server first checks to see if the instance object for the servlet has been loaded and created. If it is, execute step ④ directly, otherwise, step ②.
- ② mounts and creates an instance object of the servlet.
- ③ invokes the Init () method of the Servlet instance object.
- ④ creates a HttpServletRequest object that encapsulates the HTTP request message and a HttpServletResponse object that represents the HTTP response message, and then calls the servlet's service () Method and passes the request and response objects in as parameters.
- Before the ⑤web application is stopped or restarted, the servlet engine uninstalls the servlet and calls the servlet's Destroy () method before uninstalling.
Servlet interface Implementation Class
- Servlet Interface Sun Company defines two default implementation classes, namely: Genericservlet, HttpServlet.
- HttpServlet refers to a servlet capable of handling HTTP requests, which adds some and HTTP protocol processing to the original servlet interface, which is more powerful than the servlet interface. As a result, developers should typically inherit this class when writing a servlet, rather than implementing the Servlet interface directly.
- HttpServlet when implementing the Servlet interface, the service method is covered, and the code in the body of the method automatically determines how the user is requested, such as a GET request, and calls the HttpServlet Doget method, such as a POST request, to invoke the Dopost method. As a result, developers usually need to overwrite the Doget or Dopost method when writing a servlet, rather than overwrite the service method.
- Creating and writing Servlets through eclipse
- You inherit the Javax.servlet.http.HttpServlet class when you write the Servlet class.
- The eclipse automatically generates the following code:
Package Gacl.servlet.study;import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.HttpServletResponse; public class ServletDemo1 extends HttpServlet {/** * The Doget method of the Servlets. <br> * This method is Calle D when the a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the C Lient * @throws servletexception If an error occurred * @throws IOException If an error occurred */public void doget (Http ServletRequest request, HttpServletResponse response) throws Servletexception, IOException {response.setcontenttype (" Text/html "); PrintWriter out = Response.getwriter (); Out.println ("<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > "); Out.println ("<HTML>"); Out.println ("
- If it is a POST request, write the Dopost function, which is the GET request, and write the Doget function. However, the Web server cannot invoke the Servlet class at this time, and it needs to be configured in the. xml file.
Servlet development attention to detail
- servlet Access URL Mapping configuration
- Because the client accesses the resources in the Web server through a URL address, the servlet program must map the servlet program to a URL address if it wants to be accessed by the outside world, and this work is done using elements and elements in the. xml file.
- element is used to register a servlet, which contains two primary child elements: and, respectively, to set the name of the servlet's registration and the full class name of the servlet.
- An element is used to map an external access path to a registered servlet that contains two child elements: and, respectively, to specify the name of the servlet's registration and the external access path of the servlet.
- The same servlet can be mapped to multiple URLs, that is, the set value of the child elements of multiple elements can be the registered name of the same servlet.
- servlet access URL using * wildcard mapping
- Wildcards can also be used in URLs that the servlet maps to, but there can be only two fixed formats: one is ". Extension" and the other is preceded by a forward slash (/) and ends with "/*". For example:
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>gacl.servlet.study.ServletDemo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/*</url-pattern>
- Can match any character, so at this point you can use any URL to access the ServletDemo1 servlet. For example:
http://localhost:8080/Project Name/NVLKFMNDLMD
For some of the following mapping relationships:
Servlet1 Mapping to/abc/
Servlet2 Map to/
Servlet3 Mapping to/ABC
Servlet4 map to. Do
Problem:
When the request URL is "/abc/a.html", "/abc/" and "/" are matched, which Servlet responds
The servlet engine calls Servlet1.
When the request URL is "/ABC", both "/abc/" and "/ABC" match, which Servlet responds
The servlet engine calls Servlet3.
When the request URL is "/abc/a.do", both "/abc/" and ". Do" match, which Servlet responds
The servlet engine calls Servlet1.
When the request URL is "/a.do", the "/" and ". Do" matches, which Servlet responds
The servlet engine calls Servlet2.
When the request URL is "/xxx/yyy/a.do", the "/" and ". Do" matches, which Servlet responds
The servlet engine calls Servlet2.
The principle of matching is, "who looks more like who's looking?"
The difference between a
- servlet and a normal Java class The
- servlet is a Java class that is called by another Java program (Servlet engine) and cannot run independently, and it is run entirely by the servlet engine to control and dispatch.
- multiple servlet requests for the client, typically, the server creates only one Servlet instance object, that is, once the Servlet instance object is created, it resides in memory and serves subsequent requests until the Web container exits. The servlet instance object will not be destroyed.
- The servlet's Init method is called only once throughout the servlet's life cycle. Each access request to a servlet causes the servlet engine to invoke the Servlet's service method once. For each access request, the Servlet engine creates a new HttpServletRequest request object and a new HttpServletResponse response object. The two objects are then passed as arguments to the service () method of the servlet that it invokes, and the service method calls the Doxxx method separately, depending on the request.
- If an element is configured in an element, the Web application will mount and create an instance object of the servlet at startup, and the Init () method that invokes the Servlet instance object.
- Example:
<servlet><servlet-name>invoker</servlet-name><servlet-class> Org.apache.catalina.servlets.invokerservlet</servlet-class><load-on-startup>1</load-on-startup ></servlet>
- Purpose: Write a initservlet for the Web application, which is configured to mount at boot time, creating the necessary database tables and data for the entire Web application.
- Default servlet
- If a servlet's mapping path is just a forward slash (/), the servlet becomes the default servlet for the current Web application.
- Whenever a URL for a matching element is not found in the Web. xml file, their access requests are given to the default servlet processing, which means that the default servlet handles access requests that are not handled by all other servlets. For example:
<!--Configure ServletDemo2 as the default servlet-->8 <servlet-mapping>9 <servlet-name>servletdemo2</ Servlet-name>10 <url-pattern>/</url-pattern>11 </servlet-mapping>
- 3. When accessing a servlet that does not exist, it is processed using the configured default servlet
- In the Confweb.xml file, a servlet named Org.apache.catalina.servlets.DefaultServlet is registered, and the servlet is set to the default servlet.
- When accessing a static HTML file and picture in a Tomcat server, you are actually accessing the default servlet.
- Thread safety issues for Servlets
- When multiple clients access the same servlet concurrently, the Web server creates a thread for each client's access request and invokes the Servlet's service method on that thread, so if the same resource is accessed within the service method, It is possible to raise a thread safety issue.
- Thread-safe example:
public void doget (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {/*** Is there a thread-safety issue when multithreading concurrently accesses the code inside this method? * I variables are accessed concurrently by multiple threads, but there is no thread safety problem, because I is a local variable inside the Doget method, * when there are multiple threads accessing the Doget method concurrently, each thread has its own I variable, * each thread operates its own I variable, so there is no thread safety issue * Multithreading concurrent access to a method, if some resources (variables, collections, etc.) are defined within the method * then each thread has these things, so there is no thread safety issue */int I=1;i++;response.getwriter (). write (i); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, response);} By defining I as a global variable, there is a thread-safety problem when multiple threads concurrently access the variable i. Thread-safety problems exist only when multiple threads concurrently operate the same resource, so when writing a servlet, there is a thread-safety problem when accessing a resource (variables, collections, etc.) concurrently. So how do we solve this problem? First look at the following code: public class ServletDemo3 extends HttpServlet {int i=1;public void doget (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {/*** added synchronized, there is no thread safety problem when accessing I concurrently, * Why is there no thread safety problem after adding synchronized? * If there is a thread accessing the Servlet object now, it will first get the lock of the Servlet object * Wait until it finishes executing before returning the lock back to the Servlet object, because it first got the lock of the Servlet object, * So when there are other threads accessing this Servlet object,Since the lock has been taken away by the previous thread, the thread behind it can only wait for **/synchronized (this) {///in Java, each object has a lock, this is the Servlet object I++;try {thread.sleep ( 1000*4);} catch (Interruptedexception e) {e.printstacktrace ();} Response.getwriter (). Write (i+ "");}}
5. This is now done by adding a lock to the Servlet object to ensure that only one thread accesses the resources in the Servlet object at any time, so there is no thread-safety issue.
This approach solves the thread-safety problem, but writing a servlet is no way to deal with thread safety, and if 9,999 people visit the servlet at the same time, then the 9,999 must queue in turn.
For servlet thread-safety issues, Sun is offering a solution: let the servlet implement a Singlethreadmodel interface, if a servlet implements the Singlethreadmodel interface, The servlet engine will then invoke its service method in single-threaded mode.
Looking at the API of Sevlet, you can see that there are no methods and constants defined in the Singlethreadmodel interface, in Java, an interface that does not define any methods and constants is called a labeled interface, and one of the most typical markup interfaces that is often seen is "Serializable" , this interface also does not define any methods and constants, what is the use of the markup interface in Java? The main function is to give an object a flag, tell the JVM, what this object can do, such as the implementation of the "Serializable" Interface class object can be serialized, there is a "cloneable" interface, This is also a markup interface, by default, the object in Java is not allowed to be cloned, like real life people, not allow cloning, but as long as the implementation of the "Cloneable" interface, then the object can be cloned.
Let the servlet implement the Singlethreadmodel interface, as long as the definition of the servlet class is added to implement the Singlethreadmodel interface declaration.
The Servlet,servlet engine, which implements the Singlethreadmodel interface, still supports multithreaded concurrent access to the servlet by producing multiple servlet instance objects. Each concurrent thread invokes a separate Servlet instance object.
Implementing the Singlethreadmodel interface does not really address the thread safety of the servlet, because the servlet engine creates multiple servlet instance objects. The real problem with multithreading security is that a Servlet instance object is called simultaneously by multiple threads. In fact, in servlet API 2.4, Singlethreadmodel has been marked as deprecated (obsolete).
- In general, a servlet is a singleton, and the same instance can have multiple user access at the same time, without any problems. The question is whether the servlet has a state and whether access to those States must be synchronized. If so, only one user can access these states at the same time, which greatly reduces performance. So in general, Servlets are stateless.
"Go" Java Learning---Parsing the Java servlet work process