Summary:
Web technology has become one of the mainstream Internet Web application technologies, and Servlet is the core foundation of Java Web technology. This article first discusses the origin of the servlet from the background of the application of the request/response architecture, clarifies the motivation of the servlet, and reveals the nature of the servlet and the role it plays in the standard MVC pattern. Then, the inheritance structure of the servlet family is given, and the interfaces and abstract classes in the family are introduced, and the common practice of developing a servlet program is given. On this basis, we have illustrated the life cycle and execution flow of the servlet, and clearly demonstrated the principle of servlet. In particular, because the servlet container defaults to handling requests in single-instance multithreading, we further describe the servlet's connection to concurrency and discuss and summarize how the servlet container can handle multiple requests at the same time and how to develop a thread-safe servlet two issues. Finally, based on the structure evolution of Java WEB application, this paper gives the basic composing elements, inner relation and Function Division of MVC architecture, and gives the role of Servlet in it.
This article mainly introduces the knowledge of Servlet theory, and focuses more on the following issues:
- Why there are servlets;
- What a Servlet is;
- How the Servlet achieves the desired effect;
- The function principle of Servlet;
- Servlet and concurrency;
- The structure evolution of Servlet and Java WEB application;
- The Servlet's connection to MVC.
For more information on servlet usage, practices, and the new features of Servlets (servlet asynchronous processing, servlet non-blocking IO, and servlet file uploads), see the Companion of this article, "Servlet Overview (Practice)".
For more on Java concurrency, go to my column, Java Concurrency Programming learning notes. This column is a comprehensive record of Java concurrency programming knowledge, combined with operating system, Java memory model and related source code on the principle of concurrent programming, technology, design, the underlying implementation of in-depth analysis and summary, and continue to follow the concurrency-related technology.
Copyright Notice:
This article original nerd Rico
Author Blog address: http://blog.csdn.net/justloveyou_/
I. Servlet overview
1. The origin of the Servlet from the request/response architecture
We have previously described the request/Response Architecture in a more systematic narrative in the "Java Web Foundation-jsp Overview (bottom)" section, which we will now describe further.
A large part of the application that we are exposed to is based on the request/Response architecture , as shown in. In this architecture, it typically consists of two roles:Server and User Agent. In particular, depending on the user agent, we can divide the application into b/s mode (User agent is browser) and C/s mode . However, regardless of the mode, the Server interacts with the user Agent using the same request and response criteria, the HTTP protocol .
Generally, in the case of a browser,the role of the user Agent is to generate the corresponding HTTP request message to the server according to the request URL, and to parse (or render) the response of the server, so that the user can see a colorful page. However, if we need to complete some business logic on the Web page (for example, login verification), or need to fetch some data from the server's database as the content of the Web page, then in addition to the HTML markup that is responsible for the display, there must be code to complete these business functions, This is what we call Dynamic Web pages .
For static web pages, there is a pure HTML file on the server. When the client browser makes an HTTP request, the server can find the corresponding HTML file based on the requested URL and return the HTML code to the client browser. However, for dynamic Web pages, in addition to finding the HTML markup that needs to be displayed on the server, you must execute the required business logic, and then generate new HTML code along with the results of the business logic operation and the HTML markup that needs to be displayed. Finally, the new HTML code with the results of the business logic operation is returned to the client. to achieve the goal of Dynamic Web pages, the servlet technology, which dynamically generates HTML pages with an output stream, was created to provide dynamic, user-oriented content in a portable way.
2. The nature and role of the Servlet
Web technology has become one of the mainstream Internet Web application technologies, and Servlet is the core foundation of Java Web technology. This includes the JSP we talked about in the previous blog post, just to make up for the inadequacy of using servlets as a presentation layer. The JSP specification simplifies the implementation of the presentation layer by implementing the common static HTML and the dynamic part's mixed coding, which separates the logical content from the appearance. However, JSP does not add any functionality that is inherently not possible with the servlet, but it is more convenient to write static HTML in the JSP. In fact, thenature of JSP is still servlet, and from the perspective of the expression layer, JSP is a kind of servlet simplification.
Servlet is part of the Java EE Standard and is a small Java program running on a Web server, and more specifically, a Java class written by the servlet specification that interactively browses and modifies data to generate dynamic Web content. Note that because the servlet is a server-side applet, the servlet must be deployed in a servlet container to be used, such as Tomcat,jetty.
In the standard MVC pattern, the Servlet is used only as a controller, and the controller role is responsible for receiving the client's request, which neither responds directly to the client output nor handles user requests, but invokes the business logic component (JavaBean) to process the user request. Once the business logic component has finished processing, the controller invokes different presentation layer pages to render the processing results to the browser based on the processing results.
Two. Servlet API
The interface for Servlets is mainly in the following two packages, the servlet inheritance structure is as follows:
javax.servlet.*: storing generic servlet classes unrelated to the HTTP protocol;
javax.servlet.http.*: In addition to inheriting javax.servlet.*, it also adds functionality related to the HTTP protocol.
It is particularly important to note that all servlets must implement the Javax.servlet.Servlet interface . If we develop a servlet program that is independent of the HTTP protocol, you can inherit the Javax.servlet.GenericServlet abstract class directly, otherwise, if we develop a servlet program that is related to the HTTP protocol, you can directly inherit Javax.servlet.http.HttpServlet abstract class .
Let's take a look at the interface provided to us by the servlet interface, ServletConfig interface, Genericservlet abstract class, and HttpServlet abstract class, respectively:
(1) Interface Servlet
The Servlet interface defines the methods that all servlets must implement . where the Destroy () method, the Init () method, and the service () method are called by the servlet container. In particular, theService () method is used to process and respond to requests.
(2) Interface ServletConfig
A servlet Configuration Object used by a servlets container to pass information to a servlet during Initializa tion.
(3) Abstract Class Genericservlet
Genericservlet implements the Servlet and ServletConfig interfaces. Genericservlet May is directly extended by a servlet, although it's more common to extend a protocol-specific subclass suc H as HttpServlet.
Genericservlet makes writing servlets easier. It provides simple versions of the lifecycle methods Init and destroy and of the methods in the ServletConfig interface. Genericservlet also implements the log method, declared in the ServletContext interface.
To write a generic servlet, you need only override the abstract service method.
(4) Abstract Class HttpServlet
by inheriting HttpServlet, it is convenient to help us create an HTTP Servlet. as we can see, HttpServlet provides the appropriate handling for various HTTP requests. However, we learned from the servlet interface that the service () method is used to generate a response to the client, so how does the service () method relate to the seven HTTP request handling methods shown in the figure? Let's look at the implementation of the Service () method HttpServlet:
ProtectedvoidService (HttpServletRequest req, HttpServletResponse resp)Throws Servletexception, IOException {String method = Req.getmethod ();if (Method.equals (Method_get)) {Long lastmodified = getlastmodified (req);if (lastmodified = =-1) {doget (req, resp);}else {Long ifmodifiedsince = Req.getdateheader (header_ifmodsince);if (Ifmodifiedsince < (LastModified/1000 *) {maybesetlastmodified (resp, lastmodified); Doget (req, resp);}else {resp.setstatus (httpservletresponse.sc_not_modified);}} }Elseif (Method.equals (Method_head)) {Long lastmodified = getlastmodified (req); Maybesetlastmodified (resp, lastmodified); Dohead (req, resp); }Elseif (Method.equals (method_post)) {DoPost (req, resp);} else if (Method.equals (method_put)) {DoPut (req, resp);} else if (Method.equals (Method_delete)) {DoDelete (req, resp);} else if (Method.equals (method_options)) {doOptions (REQ,RESP);} Span class= "Hljs-keyword" >else if (Method.equals (method_trace)) {dotrace (REQ,RESP);} Span class= "Hljs-keyword" >else {//Error object[] Errargs = new Object[1]; Errargs[0] = method; errmsg = Messageformat.format ( ErrMsg, Errargs); Resp.senderror (httpservletresponse.sc_not_implemented, errmsg); }}
We know that theservice () method is used to generate a response to the client. For HttpServlet, however, the service () method will further distribute the request to the corresponding processing method according to the specific request type. since most of the time the Servlet handles all types of requests the same way, we simply rewrite the service () method to respond to all requests from the client. Alternatively, because the client's request is usually only GET and POST two, we only need to rewrite the doget () and DoPost () two methods.
In fact, the service () method in the common servlet class is exactly the same as the _jspservice () method in the Servlet class generated by the JSP translation.
Three. servlet life cycle and execution process
1. The life cycle of the servlet
When a Servlet is running in a container, the creation and destruction of its instances are not determined by the programmer, but are controlled by the Web container. A Servlet object is created with two opportunities: when the user requests it or when the app starts.
(1) When a client requests a servlet for the first time, the container creates the servlet instance, which is also the time when most servlets create instances;
(2) A servlet instance, the Load-on-startup servlet, is created as soon as the Web app starts.
But each servlet follows a lifecycle, that is, theservlet instantiation –>servlet Initialize-services --destroy. The specific process is as follows:
Create a servlet instance;
The Web container invokes the servlet's init () method to initialize the servlet. In particular, the Init () method is executed only once during the servlet's life cycle;
After the Servlet is initialized, it will always exist in the Web container in response to client requests. The default request handling and response method is to invoke the Do method corresponding to the HTTP request method;
When the Web container decides to destroy the servlet, it first calls the servlet's Destroy () method to reclaim the resource, typically destroying the servlet when the Web app is closed. Like the init () method, the Destroy () method is executed only once in the servlet's life cycle. When a Servlet object exits its lifecycle, it is responsible for releasing the resource that is occupied. A servlet may produce additional threads when running the service () method, so you need to ensure that these threads have been terminated or completed when you call the Destroy () method.
Ps: This figure is from CSDN He Jinghuan Java Study –servlet a detailed article.
2. servlet execution Process
The servlet execution process is as follows:
(1) The User Agent makes an HTTP request to the servlet container (TOMCAT);
(2) The Servle container receives the request from the User Agent;
(3) The Servle container forwards the request to the appropriate servlet based on the servlet-related configuration information in the Web. xml file;
(4) The servlet container creates a HttpServlet object for processing requests;
(5) The servlet container creates a HttpServletRequest object that encapsulates the request information into this object;
(6) The servlet container creates a HttpServletResponse object;
(7) The servlet container invokes the service method of the HttpServlet object and passes the Httpservltrequest object and the Httpservltresponse object as parameters to the HttpServlet object;
(8) HttpServlet calls the method of HttpServletRequest object, obtains the HTTP request information;
(9) HttpServlet calls the JavaBean object (business logic component) to process the HTTP request;
HttpServlet invokes the method of the HttpServletResponse object to generate the response data;
(one) The servlet container passes the result of the HttpServlet response to the User Agent.
3, Load-on-servlet
Load-on-servlet refers to servlets that are created when an app is launched, typically a servlet for background services or a servlet that needs to intercept many requests. In other words, these servlets are often used as the base servlet for applications to provide important back-office services. For example:
@WebServlet (loadonstartup=1) public class timerservlet extends HttpServlet{ Span class= "Hljs-keyword" >public void init (ServletConfig config) throws servletexception {super.init (config); Timer t = new Timer (1000,new ActionListener () //anonymous inner class {public void actionperformed (ActionEvent e) {System.out.println (new Date ()); } }); T.start (); }}
We see that this load-on-servlet does not provide a service () method, which indicates that it cannot respond to user requests, so there is no need to configure URL mappings for it. Because it cannot receive user requests, it can only be instantiated when the app starts.
It is particularly important to note that the Loadonstartup property is used to flag whether the container is loading the servlet at startup. A value of 0 or greater than 0 o'clock indicates that the container loads the servlet when the app is started, or when it is a negative or unspecified, indicating that the container is loaded when the servlet is selected. The lower the positive value, the higher the priority to start the servlet.
Four. Configuration of the servlet
In order for the servlet to respond to user requests, the servlet must be configured into a web app. Starting with the Java EE 6 (that is, servlet 3.0), there are two ways to configure a servlet, namely @WebServlet annotation configuration and the traditional Web. XML configuration, which is described in detail in my next blog, servlet Overview (practice).
Five. Servlet and concurrency
1. How the servlet container handles multiple requests at the same time
servlets use multithreading to handle multiple requests at the same time. more specifically, the Servlet relies on a line pool service request, which is actually a series of worker thread collections that contain a set of threads waiting to perform tasks. In addition, the Servlet uses a dispatch thread to manage these worker threads.
When the servlet container receives a servlet request, the dispatch thread selects a worker thread from the thread pool and passes the request to the worker thread, which then executes the servlet's service () method. When this thread is executing, if the container receives another request, the dispatch thread will also pick another worker thread from the thread pool to serve the new request, especially to note that the container does not care whether the request accesses the same servlet. when a container receives multiple requests to the same servlet at the same time, the service () method of the servlet is executed concurrently in multiple threads.
The servlet container defaults to single-instance multithreading to handle requests, reducing the overhead of generating servlet instances, increasing response times to requests, and, for Tomcat containers, We can set the number of threads in the thread pool through elements in its server.xml.
2. How to develop a thread-safe servlet
The servlet container uses multithreading to handle requests, improving performance while also causing thread-safety problems. To develop a thread-safe servlet, you should do this in several ways:
(1). thread Safety of variables: multithreading does not share local variables, so we want to use local variables in the servlet as much as possible;
(2). thread Safety for code blocks: You can use synchronized, Lock, and Atomic operations (JAVA.UTIL.CONCURRENT.ATOMIC) to guarantee collaborative access to shared variables, but be aware that To minimize the range of synchronization code, try not to use synchronization directly on service methods and response methods, which can seriously affect performance;
(3). Thread-Safe properties: The properties in the Servletcontext,httpsession,servletrequest object are thread-safe;
(4). Use the thread-safe container: Use the thread-safe container under the Java.util.concurrent package instead of the ArrayList, HashMap, and other non-thread-safe containers;
For more on Java concurrency, go to my column, Java Concurrency Programming learning notes. This column is a comprehensive record of Java concurrency programming knowledge, combined with operating system, Java memory model and related source code on the principle of concurrent programming, technology, design, the underlying implementation of in-depth analysis and summary, and continue to follow the concurrency-related technology.
Six. Servlet and MVC
The architecture of Java WEB applications has gone through the Model1 and Model2 two times. In Model1 mode, the entire WEB application is composed of almost all JSP pages, with only a small amount of JavaBean to handle database connection, access and other operations. From an engineering point of view, JSP not only acts as a performance layer, but also acts as a controller, mixing control logic and performance logic, resulting in very low code reuse rates, which makes the application extremely difficult to extend and maintain.
Model2 is already a design pattern based on the MVC architecture. In Model2, the servlet acts as a front-end controller that receives requests sent by the client, contains only the control logic and simple front-end processing in the servlet, and then the servlet invokes the JavaBean (business logic component) of the backend to process the business logic; Forwards the display logic to the appropriate JSP page based on the processing results. In Model2 mode, the model is played by JavaBean, the view is played by the JSP page, and the controller is played by the Servlet. The MODEL2 process is as follows:
More specifically, in Model2 (Standard MVC), the roles are divided as follows:
Model: By JavaBean, all the business logic and database access are implemented in model;
View: by JSP, responsible for collecting the user request parameters and the application processing results, status data presented to the user;
Controller: Performed by the Servlet, acting like a dispatcher, where all user requests are sent to the Servlet,servlet call Model to process the user request and invoke the JSP to render the result based on the processing result , or the servlet invokes the JSP directly to expose the application processing results to the user.
references
"Lightweight Java EE Enterprise Application (fourth edition)"
The role of Load-on-startup in Web. xml
Java Learning Article –servlet detailed
Servlet life cycle, how it works
Servlet Summary
How the servlet container handles multiple requests at the same time
Java Web Foundation---Servlet Overview (theory)