Detailed explanation of servlet in jsp/servlet learning II

  Servlet API overview

    The Servlet API has the following four java packages:

    1, javax.servlet, which contains the classes and interfaces that define the contract between the servlet and the servlet container.

    2, javax.servlet.http, which contains the classes and interfaces that define the contract between the HTTP servlet and the servlet container.

    3, javax.servlet.annotation, which contains annotations for servlet, filter, and listener. It also defines metadata for callout components.

    4, javax.servlet.descriptor, which contains the type of configuration information that provides programmatic login web applications.

  The core of servlet technology is servlet, which is an interface that all servlet classes must implement directly or indirectly. When writing servlets and servlet classes, implement it directly, and when extending classes that implement this interface, implement it indirectly. The servlet interface defines the contract between the servlet and the servlet container. The contract boils down to the fact that the servlet container loads the servlet class into memory and invokes specific methods on the servlet instance. In an application, there can only be one instance of each servlet type.

  The user request causes the servlet container to call the servlet's service method, passing in an instance of servletRequest and an instance of servletResponse. The current http request is encapsulated in ServletRequest, so the servlet developer does not have to parse and manipulate the raw 2 http data. ServletResponse represents the current user's HTTP response, making it easy to send a response back to the user. For each application, the servlet container also creates a servletContext instance. This object encapsulates the environment details of the context (application). There is only one servletContext per context. Each servlet instance also has a ServletConfig that encapsulates the servlet configuration.

  Servlet life cycle

  There are three methods related to the servlet life cycle: init(), servlice(), and destroy()

  init() method, but the servlet container will call this method when the servlet is requested for the first time. This method will not be called on subsequent requests. We can use this method to perform the corresponding initialization work. When calling this method, the servlet container will pass in a ServletConfig. In general, you would assign the ServletConfig to a class-level variable, so this object can be used from other points of the servlet class.

  The service() method, which is called by the servlet container whenever a servlet is requested. When writing the code, it is assumed that the servlet is to be requested here. When the servlet is requested for the first time, the servlet container calls the init method and the service method, and subsequent requests only call the service method.

  The destroy() method is called by the servlet container when the servlet is to be destroyed, which happens when the application is to be uninstalled, or the servlet container is to be shut down. Typically, cleanup code is written in this method.

  ps: servlet life cycle

  A servlet is a part of a web server and application server that runs in a servlet container (sometimes called a servlet engine, and is used to provide network services on top of sent requests and responses, decode MIME-based requests, and format MIME-based responses. .Commonly used tomcat, jboss, weblogic are all in the Servlet container), and its life cycle is managed by the container. The servlet life cycle is represented by the init(), Service(), and destroy() methods in the java.servlet.Servlet interface. The life cycle of a servlet has four phases: loading and instantiation, initialization, request processing, and destruction. 

step:

  1. When the servlet container is responsible for loading and instantiating Sevlets. A servlet instance is created when the container starts, or when the container detects that this servlet is needed to respond to the first request. When the container is started, the servlet loads the servlet class through the class loader, and then a new servlet object is completed to complete the instantiation operation. 

  2. After the instantiation operation is completed, the Init() method is called and an object that implements the ServletConfig interface is passed. In the init() method, the servlet can read configuration parameters from the deployment descriptor, or perform any other one-time activity. The init() method is called only once during the entire life cycle of a servlet class.

  3. When the servlet is initialized, the container is ready to process client requests. When the container receives a request for this servlet, it calls the servlet's service() method, passing the request and response objects as parameters. When parallel requests come in, multiple service() methods can run in separate threads at the same time. By analyzing the ServletRequest or HttpServletRequest object, the service() method processes the user's request and calls the ServletResponse or HttpServletResponse object to respond. When the servlet completes a request and responds, it waits for the next request or the server destroys it.

  4. Once the servlet container detects that a servlet is about to be unloaded, either because resources are being reclaimed or because it is being shut down, the container calls the servlet's destroy() method after all servlet service() threads. Then, the servlet can perform garbage collection and cleanup. In this way, the servlet object is destroyed. These four stages together determine the life cycle of a servlet. 

 Servlet configuration

  Common jar package files

  

      There are two commonly used configuration methods for servlet, one is in the form of annotations, and the other is in the form of web.xml

  1. By way of annotations 

    @WebServlet(name = ("FormServlet"),urlPatterns = {"/formServlet"})
    public class FormServlet extends HttpServlet {}

    The @WebServlet represents the configuration of the servlet through annotations, where the value corresponding to name represents the name of the servlet, and the urlPatterns represents the request path of the servlet. Note that "/" must be added before the request path. If initialization parameters are required, pass    

    @WebServlet(name = "GenericServletDemoServlet",urlPatterns = {"/enericServletDemo"},
      initParams = {
        @WebInitParam(name = "admin",value = "admin"),
        @WebInitParam(name = "password",value = "admin ")
    }
  )Initialize parameters in this way

  Request path http://localhost:8080/xxx project name/formServlet

  2, through the way of web.xml

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name></display-name>

    <servlet>
        <servlet-name>myServletDemo</servlet-name>
        <servlet-class>com.liu.day02.MyServletDemo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myServletDemo</servlet-name>
        <url-pattern>/myServletDemo</url-pattern>
    </servlet-mapping>

</web-app>

  Request path http://localhost:8080/xxx project name/myServletDemo  

  The servlet-name represents the name of the servlet, the servlet-class represents the class corresponding to the servlet, and the url-pattern represents the mapping path.

  The most commonly used servlet configuration is web-based configuration.

  (Any resource placed in the application directory can be directly accessed by the user as long as the user enters the resource url. If you want a resource to be accessible by the servlet, but not by the user, then it must be placed in the web- inf directory.)

  ServletRequest

    For each http request, the servlet container creates a servletRequest instance and passes it to the servlet's service method. servletRequest encapsulates information about this request.

    There are some methods in the servletRequest interface.

    public int getContentLength() returns the number of bytes in the request body, if the length in bytes is not known, this method will return -1

    public String getContentType() returns the MIME type of the request body, or null if the type is not known

    public String getProtocol(); Returns the protocol name and version of this http request.

    ......

  ServletResponse

    The javax.servlet.servletResponse interface represents a servlet response. Before calling the service method of the servlet, the servlet container first creates a servletResponse and passes it to the service method as the second parameter. servletResponse hides the complex process of sending a response to the browser.

  Common methods include the getWriter method to obtain a print stream object for sending a response to the client. setContextType sets the transfer object type

  For the rest of the common methods, please refer to the servlet related api.

  servletConfig

  When the servlet container initializes the servlet, the servlet container passes a servletconfig to the servlet's init method. servletconfig encapsulates configuration information that can be passed to a servlet via @webservlet or a deployment descriptor. In this way, each piece of information passed in is called an initial parameter, and an initial parameter has two elements: key and value.

  servletContext

  servletContext represents the servlet application. There is only one context per web application. In a distributed environment where an application is deployed to multiple containers at the same time, each web application on the Java virtual machine will have a ServletContext object.

  HttpServlet

  The HttpServlet class overrides the javax.servlet.GenericServlet class. When using HttpServlet, it is also necessary to use the HttpServletRequest and HttpServletResponse objects that represent the Servlet request and Servlet response respectively. The HttpServletRequest interface extends javax.servlet.ServletRequest, and HttpServletResponse extends javax.servlet.ServletResponse.

Guess you like

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