Servlet technology in practice

The Servlet framework is composed of two java packages: javax.servlet and javax.servlet.http.     

javax.servlet contains classes that support common protocol-agnostic servlets.

javax.servlet.http includes special support for the HTTP protocol.
  The core of the servlet framework is the javax.servlet.Servlet interface, and all servlets must implement this interface. Five methods are defined in the Servlet interface, three of which represent the life cycle of the servlet:
  (1) init method, responsible for initializing the Servlet object
  (2) service method, responsible for initially responding to customer requests
    (3) destroy method, When the servlet object exits the life cycle, it is responsible for releasing the occupied resources
Servlet technology

 

As can be seen from the above figure, GenericServlet implements the Servlet interface, and HttpServlet extends GenericServlet. When users develop their own Servlet classes, they can extend the HttpServlet class . If the Servlet class extends the HttpServlet class, it is usually not necessary to implement the service method because the HttpServlet class already implements the service method. In the service method of HttpServlet, the information of the HTTP request method is first obtained from the HttpServletRequest object, and then the corresponding method is called according to the request method.
The declaration form of this method is as follows:
protected void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
In the service method of HttpServlet, there are two parameters: HttpServletRequest and HttpServletResponse, these two classes extend javax.servlet.ServletRequest and javax.servlet.ServletResponse interface.
ServletRequest interface: The ServletRequest interface encapsulates the client request information, such as client request method, parameter name and parameter value, the protocol the client is using, and the information of the remote host that sends the client request. The ServletRequest interface also provides a ServletInputStream that directly reads the client request data stream in binary format. Subclasses of ServletRequest can provide servlets with more data related to specific protocols.
ServletRequest interface: ServletRequest interface provides servlets with methods to return response results. It allows the servlet to set the length and MIME type of the returned data, and provides the output stream ServletOutputStream. ServletResponse subclasses can provide more protocol-specific methods.

HttpServlet can generate corresponding HTTP response results according to HTTP requests sent by clients. HttpServlet first has to read the content of the HTTP request. The servlet container is responsible for creating the HttpRequest object and encapsulates the HTTP request information into the HttpRequest object, so that any part of the message in the HTTP request can be easily read by calling the related methods of HttpServletRequest.

 

Servlet life cycle

 

Stage 1: Servlet implementation class loading

 

(1) When all web-servers load Servlet implementation classes, they will search the subdirectories lib and classes in the WEB-INF directory of the web-app root directory, search for *.jar files in the lib directory, and search in the classes directory *.class file; it will traverse the web.xml configuration file in the WEB-INF directory, and load the corresponding class file according to the content of the Servlet-class sub-tag under the Servlet tag in the file.

(2) The public jar packages of all web-apps in the webapps directory are stored in the subdirectory lib of the common directory under the root directory of the tomcat installation. When the web-app uses the jar package, it first searches for the lib in this app. jar package, the jar package will be found in the lib of the common directory;

(3) The method of loading the Servlet implementation class when the web server starts (configure web.xml in the WEB-INF directory)

Add sub-tags to the Servlet tags corresponding to the Servlet implementation classes in the web.xml file, such as:

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

The text inside the tag should be a positive integer. When sub-tags are added to the servlet tags corresponding to multiple servlet implementation classes, the corresponding servlet implementation class is loaded according to the size of the integer corresponding to the text; the smaller the integer value, the more reliable the loading order. front; when the values ​​are equal, the loading order is determined by the web-server.

 

Stage 2: Creation and initialization of servlet objects

 

(1) Most web-servers will load the Servlet implementation class when the client accesses the server for the first time, create the object and execute the initialization method, (if the server is set to load at startup, the object will be created and the initialization method will be executed when the server starts. When the client accesses the server for the first time, it directly enters the service phase to execute the service method); in the future, each client will not call the init method when sending a request, that is to say, it can only be called once. The initialization method of a servlet object is executed only once;

(2) Set initialization parameters for the Servlet object (configure web.xml in the WEB-INF directory)

1> Add sub-tags to the Servlet tag corresponding to the Servlet implementation class in the web.xml file, such as:

<init-param>

<param-name>parameter name</param-name>

<param-value>parameter value</param-value>

</init-param>

Each pair of init-param tags can only set one initialization parameter. If you want to set multiple initialization parameters, you need to repeat the above four lines of code; the parameter name generally cannot be changed, because we need to use it in the java program; the parameter value can be modified.

2> Override the parameterless init() method in the Servlet implementation class, and use getInitParameter("parameter name") inside the method to obtain the corresponding parameter value. This method is used in both the javax.Servlet.ServletConfig and javax.Servlet.GenericServlet classes. There is a definition, and the latter is generally used (that is, directly use getInitParameter("parameter name") in the Servlet implementation class to obtain the corresponding parameter value);

3> HttpServlet directly inherits the init(ServletConfig) method in the GenericServlet class. The init() method of the GenericServlet class has two forms: conventional initialization, initialization controlled by initialization parameters 

   public void init()throws ServletException{} //Methods without parameters can be called

   public void init(ServletConfig config)throws ServletException{

   this.config=config;//Initialize member variable config

   init(); //The init method without parameters is called directly here.

 }

 

General initialization: create and load some data used in the servlet life cycle, such as establishing database connection sharing for the request to be processed, loading data files into HashMap, etc.

 

initialization controlled by initialization parameters

   1. The name and value of the initialization parameter can be specified by adding the init-param sub-element to the servlet element of web.xml

   2. In the init method of the servlet, call getServletConfig to obtain a reference to the ServletConfig object

   3. Call the getInitParameter method of ServletConfig with the parameter name of the init method as the parameter, and the return value is the value of the init parameter, or null if the init parameter is not found in the web.xml file.

 

The first line in the init(ServletConfig) method initializes the config member variable, and the getInitParameter("parameter name") method in the GenericServlet class returns getConfig().getInitParameter("parameter name"); when the Servlet implementation class directly uses getInitParameter( "parameter name"), because the member variable config is not initialized, getConfig() will return null; so a null pointer exception will occur, so you should always add super.init(con) to the first line.

 

 Stage 3: The servlet object provides service according to the client's request

 

(1) The HttpServlet class inherits from the Servlet implementation class javax.Servlet.GenericServlet, and the service() method overridden in the HttpServlet class completes the process of converting from one service method to multiple methods (doGet, doPost, doDelete, etc.). The function of the service method is changed, doGet and doPost respectively indicate that it is called when the client "method" attribute is set to get and post; only one of the functional methods needs to be overridden in the subclass of HttpServlet;

(2) The service method will be called when the server is accessed. The service method may be called multiple times during the life cycle of the servlet object. After the web-server is started, some of the resources exposed in the server will be in the network. When the host (client) accesses the same resource in the server concurrently, the server will open multiple threads to process different requests. When multiple threads process the same object at the same time, there may be errors of concurrent access to data. When multiple threads process the same variable at the same time (for example: write operations to the same file), and there are read and write operations, you must consider whether to add synchronization (synchronized). For pure single thread, the system performance is greatly weakened; it is only necessary to access the same object safely by multiple threads;

The things that need to be synchronized in servlet are: member variables, network resources, files, static variables, database connections, etc., thread synchronization and security issues must be considered when using these.

 

Stage 4: Destruction of the Servlet object (destroy() method)

 

When the servlet object in the program is no longer used, the web-server may destroy the object, and different web-servers have different destruction times; the destruction of a servlet object (destroy() method) is only executed once;

We can close the database, close the stream, terminate the background thread and other finishing work in this method. Note: Do not store persistent objects in memory, and transfer them to external storage devices at the end of the program; because when the web-server exits abnormally (caused by power failure and other factors), the data cannot be transferred in time, which will cause data lost.

 

 

 

From another perspective:

Servlet life cycle :

        There are three types of events in the life of each servlet instance, which correspond to the three methods awakened by the servlet engine.
        (1) init()
       When a servlet is loaded for the first time, the servlet engine calls the servlet's init() method, only once. If a servlet needs special initialization needs, servlet writers can override this method to perform initialization tasks. This is an optional method. If a servlet does not require initialization, its parent class's init method will be called by default. The system guarantees that the servlet will not be called to process any requests until the init method is completed.
        (2)service()
           This is the most important method of the servlet and is where the request is actually processed. For each request, the servlet engine will call the servlet's service method, passing it the servlet request object and the servlet response object as parameters.
        (3)destroy()    

        This is an optional method relative to init. It is called by the servlet engine when the servlet is about to be unloaded. This method is used to clear and release the resources allocated in the init method.

     The life cycle of a servlet can be divided into the following steps:

          1 Load the servlet, which is generally performed dynamically. However, servlets usually provide a managed option for forcing a specific servlet to be reloaded and initialized at servlet startup.

          2 The server creates a servlet instance.

          3 The server calls the init method of the servlet.

          4 A client request arrives at the server.

          5 The server creates a request object.

          6 The server creates a response object.

             7 The server activates the service() method of the servlet, passing the request object and the response object as parameters.

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

          9 service()方法使用响应对象的方法。将响应传回服务器,最终到达客户端。service()方法可以激活其他方法以处理请求。如doGet(),doPost()或者程序员自己开发的其他方法。

         10 对于更多的客户端请求,服务器创建新的请求和响应对象,仍然激活此Servlet的service()方法,将这两个对象作为参数传给它,如此重复以上的循环,但无需再次调用init()方法,Servlet一般只初始化一次。

         11 当服务器不再需要Servlet时,比如当服务器要关闭时,服务器调用Servlet的destroy()方法。

 

 

Servlet的工作过程

         Servlet的主要功能在于交互式的浏览和修改数据,生成动态Web内容。这个基本工作过程如下:

        (1) 客户端发送请求至服务器端。

        (2) 服务器上的Web容器装入Servlet,并为Servlet进程创建线程。请注意,Servlet是在出现第一个请求时装入的,在服务器关闭之前不会卸载它。Servlet也可以配置为Web应用程序启动时自动装载。

        (3)Web容器将请求信息发送至Servlet。

        (4)Servlet生成响应内容并将其返回给Web容器。响应内容动态生成,通常取决于客户端的请求。

        (5)Web容器将响应返回给客户端。

        (6)服务器关闭或者Servlet空闲时间超过一定限度时,调用destroy()方法退出

 

 

 

 Servlet容器响应Web客户请求的步骤

 

1:Web客户向Servlet容器发出HTTP请求;
2:Servlet容器解析Web客户的HTTP请求;
3:Servlet容器创建一个HttpRequset对象,在这个对象中封装了HTTP请求信息;
4:Servlet容器创建一个HttpResponse对象;
5: The servlet container calls the service method of HttpServlet, and passes the HttpRequest and HttpResponse objects as parameters of the service method to the HttpServlet object;
6: HttpServlet calls relevant methods of HttpResponse to obtain HTTP request information
7: HttpServlet calls relevant methods of HttpResponse to generate response data
8: The servlet container passes the response result of the HttpServlet to the web client

 

What is the difference between forward() and redirect() in SERVLET API?


Answer: The former is only the redirection of the control right in the container, and the redirected address will not be displayed in the address bar of the client browser; the latter is a complete redirection, the browser will get the redirected address and restart the Send request link. In this way, the link address after the jump can be seen from the address bar of the browser. Therefore, the former is more efficient, and when the former can meet the needs, try to use the forward() method, and this also helps to hide the actual link. In some cases, for example, you need to redirect to a resource on another server, you must use the sendRedirect() method.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326678795&siteId=291194637