In-depth study and understanding of Servlet (1)

In-depth study and understanding of Servlet (1)

Servlet workflow

img

Servlet definition

Servlet (Server Applet) is the abbreviation of Java Servlet, called small service program or service connector. It is a server-side program written in Java, which is independent of platform and protocol. The main function is to browse and generate data interactively. Dynamic web content.

Servlet in a narrow sense refers to an interface implemented by the Java language, and Servlet in a broad sense refers to any class that implements this Servlet interface. In general, people understand Servlet as the latter. Servlet runs in an application server that supports Java. In principle, Servlet can respond to any type of request, but in most cases Servlet is only used to extend the Web server based on HTTP protocol.

The first to support the Servlet standard was JavaSoft's Java Web Server. Since then, some other Java-based Web servers have begun to support the standard Servlet.

Implementation process

The first to support Servlet technology is JavaSoft's Java Web Server. Since then, some other Java-based Web Servers began to support the standard Servlet API. The main function of Servlet is to interactively browse and modify data and generate dynamic Web content. This process is:

  1. The client sends a request to the server;
  2. The server sends the request information to the Servlet;
  3. The servlet generates the response content and sends it to the server. The response content is generated dynamically, usually depending on the client's request;
  4. The server returns the response to the client.

Life cycle

  1. The client requests the Servlet;
  2. Load the Servlet class into memory;
  3. Instantiate and call the init() method to initialize the Servlet;
  4. service() (call doGet() or doPost() depending on the request method, in addition to doHead(), doPut(), doTrace(), doDelete(), doOptions(), destroy()).
  5. Load and instantiate the servlet. This operation is generally performed dynamically. However, Server usually provides a management option to force loading and initializing a specific Servlet when the Server starts.

Server creates an instance of Servlet

The first client's request arrives at the Server

Server calls Servlet's init() method (it can be configured to be called when Server creates Servlet instance, configure the tag under the tag in web.xml, the configured value is an integer, the smaller the value, the higher the startup priority of the servlet)

A client's request arrives at the Server

  1. Server creates a request object to process client requests

  2. Server creates a response object to respond to client requests

  3. Server activates the service() method of Servlet, passing request and response objects as parameters

  4. The service() method obtains information about the requested object, processes the request, accesses other resources, and obtains the required information

The service() method uses the method of the response object to send the response back to the Server and finally to the client. The service() method may activate other methods to process the request, such as doGet() or doPost() or a new method developed by the programmer himself.

For more client requests, Server creates new request and response objects, still activates the service() method of this Servlet, and passes these two objects to it as parameters. Repeat the above cycle without calling the init() method again. Generally, Servlet is initialized only once ( only one object ). When Server no longer needs Servlet (usually when Server is closed), Server calls Servlet's destroy() method.

The following figure shows a typical Servlet life cycle scheme:

Insert picture description here

  1. The first HTTP request to reach the server is delegated to the servlet container.

  2. The servlet container loads the servlet before calling the service() method.

  3. Then the Servlet container processes multiple requests generated by multiple threads, and each thread executes the service() method of a single Servlet instance.

Operating mode

The client sends a request to the server

The server starts and calls the Servlet, and the Servlet generates the response content according to the client request and sends it to the server

The server returns the response to the client

version

version date JAVA EE/JDK version characteristic
Servlet 4.0 2017.10 JavaEE 8 HTTP2 [1]
Servlet 3.1 2013.5 JavaEE 7 Non-blocking I/O, HTTP protocol upgrade mechanism
Servlet 3.0 2009.12 JavaEE 6, JavaSE 6 Pluggability, Ease of development, Async Servlet, Security, File Uploading
Servlet 2.5 2005.10 JavaEE 5, JavaSE 5 Requires JavaSE 5, supports annotation
Servlet 2.4 2003.11 J2EE 1.4, J2SE 1.3 web.xml uses XML Schema
Servlet 2.3 2001.8 J2EE 1.3, J2SE 1.2 Addition of Filter
Servlet 2.2 1999.8 J2EE 1.2, J2SE 1.2 Becomes part of J2EE, introduced independent web applications in .war files
Servlet 2.1 1998.11 unspecified First official specification, added RequestDispatcher, ServletContext
Servlet 2.0 JDK 1.1 Part of Java Servlet Development Kit 2.0

new features

Servlet 2.2

: The concept of self-contained Web applications is introduced.

servlet 2.3
Come out in October 2000

The most significant change in Servlet API 2.3 is the addition of filters

Servlet 2.3 adds the functions of filters and filter chains. Introduced the concept of context and session listeners, when the context or session is initialized or will be released, and when binding attributes or unbinding context or session, you can monitor the class.

servlet 2.4
Launched in November 2003

Servlet 2.4 has added several features that have attracted attention. There is no new content that is particularly prominent. Instead, more effort has been spent on deliberation and clarification of some of the features that existed before, and verification of some less rigorous places.

Servlet 2.4 adds new minimum requirements, a new method of monitoring request, a new method of processing response, new internationalization support, several processing of RequestDispatcher, a new request listener class, a description of session, and a new based Schema and has the release descriptor of J2EE elements. This document specification has been revised comprehensively and strictly, removing some obscure factors that may affect cross-platform release. All in all, this specification adds four new classes, seven new methods, and one new constant. It is no longer recommended to use one class.

Note: After changing to Schema, two functions are mainly enhanced:

  1. Elements are not set in order;

  2. More powerful verification mechanism.

mainly reflects in:

  1. Check whether the value of the element is a legal value

    Check whether the value of the element is a legal text character or numeric character

    Check if the names of Servlet, Filter, EJB-ref and other elements are unique

  2. Added four filter settings: REQUEST, FORWARD, INCLUDE and ERROR.

  3. 新增 Request Listener、Event和Request Attribute Listener、Event。

  4. Cancel the SingleThreadModel interface. When a servlet implements the SingleThreadModel interface, it can ensure that only one thread executes the servlet at the same time.

  5. Can be Servlet.

  6. Some new methods have been added to the ServletRequest interface.

public String getLocalName()public String getLocalAddr()public int getLocalPort()public int getRemotePort()

Servlet 2.5

Servlet 2.5 released in September 2005

Introduction of some changes in Servlet 2.5:

  1. Based on the latest J2SE 5.0 development.

  2. Support annotations.

  3. Several configurations in web.xml are more convenient.

  4. A few restrictions have been removed.

  5. Optimized some examples

The changes to the listener for each version of Servlet include:

  1. Servlet 2.2 and jsp1.1

新增Listener:HttpSessionBindingListener

New Event: HttpSessionBindingEvent

  1. Servlet 2.3 and jsp1.2

新增Listener:ServletContextListener,ServletContextAttributeListener

,HttpSessionListener,HttpSessionActivationListener,HttpSessionAttributeListener

新增Event: ServletContextEvent,ServletContextAttributeEvent,HttpSessionEvent

  1. Servlet 2.4 和 jsp2.0

新增Listener:ServletRequestListener,ServletRequestAttribureListener

新增Event: ServletRequestEvent,ServletRequestAttributeEvent

Servlet 3.0

As a member of the Java EE 6 specification system [2], Servlet 3.0 is released along with the Java EE 6 specification. This version provides several new features on the basis of the previous version (Servlet 2.5) to simplify the development and deployment of Web applications. The introduction of several of these features made developers very excited, and also won praise from the Java community: [3]

  1. Asynchronous processing support: With this feature, the servlet thread no longer needs to be blocked until the business processing is completed to output the response, and finally the servlet thread is terminated. After receiving the request, the servlet thread can delegate the time-consuming operation to another thread to complete, and return to the container without generating a response. In view of the time-consuming business processing, this will greatly reduce the occupation of server resources and increase the speed of concurrent processing. [3]
  2. New annotation support: This version adds a number of annotations to simplify the declaration of Servlet, Filter and Listener. This makes the web.xml deployment description file no longer required from this version. Of it. [3]
  3. Pluggability support: Developers who are familiar with Struts2 will definitely remember its integration features with various common frameworks including Spring through plug-ins. Encapsulate the corresponding plug-in into a JAR package and put it in the classpath, and then these plug-ins can be automatically loaded when Struts2 is running. Now Servlet 3.0 provides similar features. Developers can easily extend the functions of existing Web applications through plug-ins without modifying the original applications. [3]

Servlet 4.0

From 3.1 to 4.0 will be a major change to the Servlet protocol, and the key to the change is the support for HTTP/2. HTTP2 will be the first new version of the HTTP protocol since the standardization of the HTTP1.1 protocol at the end of the last century. Compared with HTTP1.1, HTTP2 will bring many enhancements. In the draft proposal, Shing Wai listed some new features of HTTP2, and these features are exactly the new features he hopes to implement in the Servlet 4.0 API and expose to users. These new features are as follows: [4]

  1. Request/Response multiplexing
  2. Stream Prioritization
  3. Server Push
  4. HTTP1.1升级(Upgrade from HTTP 1.1)

specification

  1. Simplify development

  2. Easy to deploy

  3. Support Web2.0 principles

In order to simplify the development process, Servlet 3.0 introduced annotations, which makes the web deployment descriptor web.xml no longer a necessary choice.

Pluggability

When using any third-party framework, such as Struts, JSF or Spring, we all need to add the corresponding Servlet entry in web.xml. This makes web descriptors cumbersome and difficult to maintain. The new pluggable features of Servlet3.0 make web applications modular and easy to maintain. The pluggability achieved through web fragment reduces the burden on developers, and there is no need to configure many servlet entries in web.xml.

Asynchronous Processing Asynchronous Processing

Another notable change is that Servlet 3.0 supports asynchronous processing, which is very useful for AJAX applications. When a Servlet creates a thread to handle certain requests, such as querying a database or message connection, this thread has to wait until it obtains the required resources before it can perform other operations. Asynchronous processing avoids this blocking by running threads to perform other operations.

Apart from the features mentioned here, several other enhancements have been made to the existing API. The sections towards the end of the article will explore these features one by one in detail.

In addition to these new features, Servlet 3.0 has also made some improvements to the existing API, which we will introduce at the end of this article.

Annotations in Servlet Servlet****

A major change in Servlet 3.0 is to support annotations. Using annotations to define servlets and filters saves us from having to define corresponding entries in web.xml.

@WebServlet

@WebServlet is used to define a servlet in a web application. This annotation can be applied to inherit HttpServlet. This annotation has multiple attributes, such as name, urlPattern, initParams, and we can define the behavior of the servlet with the attributes of the user. The urlPattern attribute must be specified.

Programming interface

HTTPServlet uses an HTML form to send and receive data. To create an HTTPServlet, please extend the HttpServlet class, which is a subclass of GenericServlet that uses special methods to process HTML forms. HTML forms are defined by and tags. Forms typically contain input fields (such as text input fields, check boxes, radio buttons, and select lists) and buttons for submitting data. When submitting information, they also specify which servlet (or other program) the server should execute. The HttpServlet class contains init(), destroy(), service() and other methods. The init() and destroy() methods are inherited.

(1) init() method

In the lifetime of a servlet, the init() method is executed only once. It is executed when the server loads the servlet. The server can be configured to load the servlet when the server is started or the client accesses the servlet for the first time. No matter how many clients access the Servlet, init() will not be executed repeatedly.

The default init() method usually meets the requirements, but it can also be overridden with a custom init() method, which typically manages server-side resources. For example, it is possible to write a custom init() to load GIF images only once, to improve the performance of the servlet to return GIF images and contain multiple client requests. Another example is to initialize a database connection. The default init() method sets the initialization parameters of the servlet and uses its ServletConfig object parameters to start the configuration. Therefore, all servlets that override the init() method should call super.init() to ensure that these tasks are still performed. Before calling the service() method, make sure that the init() method has been completed.

(2) service() method

The service() method is the core of Servlet. Whenever a client requests an HttpServlet object, the service() method of the object will be called, and a "request" (ServletRequest) object and a "response" (ServletResponse) object are passed to this method as parameters. The service() method already exists in HttpServlet. The default service function is to call the do function corresponding to the HTTP request method. For example, if the HTTP request method is GET, doGet() is called by default. The servlet should override the do function for the HTTP methods supported by the servlet. Because the HttpServlet.service() method checks whether the request method calls the appropriate processing method, it is not necessary to override the service() method. Just overwrite the corresponding do method.

Servlet response can be of the following types:

An output stream that the browser interprets according to its content type (such as text/html).

An HTTP error response is redirected to another URL, servlet, JSP.

(3) doGet() method

When a client sends an HTTP GET request through an HTML form or directly requests a URL, the doGet() method is called. The parameters related to the GET request are added to the back of the URL and sent with the request. When the server-side data will not be modified, the doGet() method should be used.

(4) doPost() method

When a client sends an HTTP POST request through an HTML form, the doPost() method is called. The parameters related to the POST request are sent from the browser to the server as a single HTTP request. When you need to modify the server-side data, you should use the doPost() method.

(5) destroy() method

The destroy() method is executed only once, that is, it is executed when the server is stopped and the servlet is uninstalled. Typically, the servlet is shut down as part of the server process. The default destroy() method usually meets the requirements, but it can also be overridden, typically to manage server-side resources. For example, if the servlet accumulates statistics at runtime, you can write a destroy() method that saves the statistics in a file when the servlet is not loaded. Another example is closing the database connection.

When the server uninstalls the servlet, it will call the destroy() method after all the service() method calls are completed, or after the specified time interval has passed. A servlet may generate other threads when running the service() method, so please make sure that these threads have been terminated or completed when calling the destroy() method.

(6) getServletConfig() method

The getServletConfig() method returns a ServletConfig object, which is used to return initialization parameters and ServletContext. The ServletContext interface provides information about the servlet's environment.

(7) getServletInfo () method

The getServletInfo() method is an optional method that provides information about the servlet, such as author, version, copyright.

When the server calls the service(), doGet() and doPost() methods of the sevlet, it needs the "request" and "response" objects as parameters. The "request" object provides information about the request, and the "response" object provides a communication path for returning response information to the browser.

The related classes in the javax.servlet software package are ServletResponse and ServletRequest, and the related classes in the javax.servlet.http software package are HttpServletRequest and HttpServletResponse. Servlet communicates with the server through these objects and ultimately with the client. Servlet can learn the client environment, server environment information and all the information provided by the client by calling the method of the "request" object. The servlet can call the method of the "response" object to send a response, which is ready to be sent back to the client.

Common containers

Tomcat, Jetty, resin, Oracle Application server, WebLogic Server, Glassfish, Websphere, JBoss, etc. (The server that provides Servlet function is called Servlet container. For web programs, the function of Servlet container is equivalent to the function of the operating system in the desktop program, providing some programming infrastructure)

Suggest

In a Web application, a servlet may be accessed by multiple users at the same time. At this time, the Web container will create a thread for each user to execute the Servlet. If the Servlet does not involve the issue of shared resources, you do not need to care about multithreading. But if the servlet needs to share resources, you need to ensure that the servlet is thread-safe.

Here are some suggestions for writing thread-safe servlets:

  1. Use the local variables of the method to save the proprietary data in the request. For the local variables defined in the method, each thread entering the method has its own copy of the method variables. No thread will modify the local variables of other threads. If you want to share data between different requests, you should use sessions to share such data.

  2. Only use Servlet member variables to store data that will not change. Some data does not change during the servlet life cycle, and is usually determined at the beginning. These data can be saved using member variables, such as database connection names, paths to other resources, and so on.

  3. Synchronize member variables that may be requested to be modified. Sometimes data member variables or environment attributes may be requested to be modified. When accessing these data, they should be synchronized to avoid multiple threads modifying these data at the same time.

  4. If the servlet accesses external resources, then these resources need to be accessed synchronously. For example, suppose a servlet wants to read and write data from a file. When a thread reads and writes a file, other threads may also be reading and writing the file. File access itself is not thread-safe, so you must write code that accesses these resources synchronously. When writing a thread-safe servlet,

The following two methods should not be used:

  1. A SingleThreadModel interface is provided in the Servlet API. The Servlet implementing this interface has only one thread running at a time when requested by multiple clients. This interface has been marked deprecated.

  2. Synchronize with doGet() or doPost() method. If you must use synchronization code in a servlet, you should try to synchronize on the smallest code block range. The smaller the synchronization code, the better the servlet execution. )

Reference source

Baidu Encyclopedia

https://baike.baidu.com/item/servlet/477555?fr=aladdin#11

More excellent articles

Elementary school students in java
https://blog.csdn.net/shang_xs

In-depth study and understanding of Servlet (two)
https://blog.csdn.net/shang_xs/article/details/90376489

Please see GitHub for the complete code and related dependencies

https://github.com/dwyanewede/project-learn/tree/master/src/main/java/com/learn/demo/interfaces/loan/product

Official account recommendation

Insert picture description here

Guess you like

Origin blog.csdn.net/shang_xs/article/details/90371068