On Servlet, Tomcat

Vigor Jsp To start the tour, started learning Java web programming. In the here and everyone involved Jsp simple to understand two important concepts: Servlet, Tomcat.

Servlet (Server Applet) is a Java Servlet short, called the small connector service programs or services, written in Java Server-side program, with a platform-independent and protocol features, the main function is to interactively browse and generate data, generate dynamic Web content.

Refers to a narrow Servlet interface to the Java language, broadly refers to any Servlet class implements the Servlet interface, under normal circumstances, people will understand Servlet for the latter. Servlet running on Java-enabled application servers. In principle, Servlet can respond to any type of request, but in most cases only used to extend the Servlet Web server based on HTTP protocol.

Vigor interpret it this way: Servlet is written in Java and platform-independent protocol and cross-platform Web component, managed by Servlet container, dynamically extend the functionality of the server, and a "request-response" model to provide Web services.

Tomcat is a core project of the Apache Software Foundation (Apache Software Foundation) in Jakarta project by the Apache , Sun and other companies and individuals to develop from. Thanks to Sun's involvement and support, the latest Servlet and JSP specifications can always be reflected in Tomcat, Tomcat 5 supports the latest Servlet 2.4 and JSP 2.0 specification. Because Tomcat advanced technology, stable performance, and it's free, so loved by fans of Java and has been recognized by some software developers become more popular Web application server.

Vigor interpret it this way: Tomcat is a free open source lightweight Web application server (similar to Microsoft's iis).

Vigor There is also a brief introduction TomEE:

Tomcat has been a subset of J2EE or JavaEE, Web server and a separate container, do not support JTA does not support EJB JPA, etc., and is one of TomEE validated by Java EE6 JavaEE engine, Tomcat + Java EE = TomEE.
The Apache's OpenEJB, Apache OpenWebBeans, Apache OpenJPA, Apache MyFaces TomEE the like packaged.
In this way, TomEE on and GlassFish, JBoss, and Apache Geronimo in direct competition peer relationship. JavaEE developer can develop in line with the standard product application, will be able to run on TomEE.

Tomcat Servlet and then the relationship is easy to understand: Servlet is running in a Tomcat servlet container, Tomcat container is responsible for client requests to the Servlet, Servlet business processes and routes the response back to the client.

Refer to the diagram:

As can be seen from the figure, JSP "request - response" bottom Zanghuoleihuo Web services are basically Servlet undertake. The following diagram feel that digging and Servlet looks quite like, ha ha.

Vigor and then continue to share with everyone Servlet life cycle:

1. Loading and instantiation: to load and instantiate the Servlet container objects;

2. Initialization: call the init () method initializes;

3. The request processing: calling service () method to process a client request;

4. Service Termination: call destroy () method releases the resources, marked itself recyclable;

5.GC Recovery: is garbage collected.

Then we go in depth Vigor and viewed together.
Let's look at the working process of the Web server Servlet when interacting with clients:

1. The client sends a request to the Web server;
after 2. Web server receives a request sent to the Servlet;
3. For this purpose the Servlet container generates an instance object;
corresponding method ServletAPI in Example 4. Servlet to the client object invokes HTTP request is processed, and then returns the results of the processing in response to the Web server;
5. the Servlet response from the Web server object instance structure received back to the client.

Vigor for everyone to prepare a map for easy everyone a clearer understanding:

The following Vigor to explain to each of the steps in the Servlet life cycle:

1. Loading and instantiation:

  Servlet container is responsible for loading and instantiating Servlet. When the Servlet container is started, the container is detected or need this Servlet to respond to the first request, creating Servlet examples. When the Servlet container is started, it must be required to know in what position Servlet class, Servlet container Servlet class can be loaded by the class loader from the local file system, remote file systems, or other network services, successfully loaded, the container creates examples of the Servlet. Because the container is to create an instance of the Java Servlet reflection API, call the default constructor (ie constructor with no arguments) Servlet, so we in the preparation of Servlet class, and should not provide a constructor with parameters.

2. Initialize

  After Servlet is instantiated, the Servlet container calls the init () method initializes the object. The purpose is to allow Servlet initialization of the object to complete some initialization work before the client requests, such as establishing a database connection, access to configuration information. For each instance of a Servlet, init () method is called once. During initialization, Servlet container ServletConfig object instance can be used for its preparation (arrangement in web.xml) Web application configuration information from the parameter information of the initialization. During initialization, if an error occurs, Servlet instance can throw an exception or ServletException UnavailableException exceptions to notify the container. ServletException for indicating abnormal general failed to initialize, for example, find no initialization parameters; and a container for informing the abnormality UnavailableException Servlet instance is not available. For example, the database server does not start, the database connection can not be established, Servlet can throw an exception UnavailableException pointed out to the container it temporarily or permanently unavailable.

I. How to configure the Servlet initialization parameters?

   Tag in web.xml defined in the Servlet, for example:

    <servlet>
         <servlet-name>TimeServlet</servlet-name>
         <servlet-class>com.allanlxf.servlet.basic.TimeServlet</servlet-class>
        <init-param>
            <param-name>user</param-name>
            <param-value>username</param-value>
       </init-param>
       <init-param>
           <param-name>blog</param-name>
           <param-value>
https://blog.csdn.net/xuwei_net</param-value>
       </init-param>

    </servlet>

Two initialization parameters to configure user and blog their values are username and https://blog.csdn.net/xuwei_net , so that later you want to modify the user name and blog address does not need to modify the Servlet code, just modify configuration files .

II. How to read the Servlet initialization parameters?

       ServletConfig defined as a method for reading information initialization parameters:

       public String getInitParameter(String name)

          Parameters: name of the initialization parameter.
          Returns: the value of initialization parameter, if not configured, returns null.

   III.init (ServletConfig) method execution times

       In the Servlet life cycle, the method is performed once.

IV.init (ServletConfig) method with a thread

     The method is performed in a single-threaded environment, so developers do not consider thread safety issues.

V.init (ServletConfig) method with aberrant

   This method can be thrown during execution ServletException to notify the Web server Servlet instance initialization failed. Once ServletException throw, Web server, client requests will not be handed over to the Servlet instance to handle, but the report failed to initialize exception information to the client, the Servlet instance will be destroyed from memory. If the request to the new, Web server creates a new instance of Servlet, and perform a new instance of the initialization operation

3. Request Processing

  Servlet Servlet container calls the service () method to process the request. It should be noted that, before the method call, init () method must run successfully in service (). In service () method, Servlet examples ServletRequest object information obtained by the client and request information, after processing the request, calling the object method ServletResponse setting response information. During service () method performs, if an error occurs, Servlet examples ServletException can throw an exception or exception UnavailableException. If the exception indicates UnavailableException example permanently unavailable, Servlet container calls the instance destroy () method, the instance is released. Any subsequent request for instance, the container will receive the transmitted HTTP 404 (requested resource is not available) response. If the exception indicates UnavailableException example is temporarily unavailable, the request is temporarily unavailable at any time period used, the instance of the container will receive the transmitted HTTP 503 (server is temporarily busy and can not process the request) response. 

Responsibilities I. service () method

     service () method Servlet core method, the client's business logic should be executed within the method, the development process of a typical service method is as follows:

    Parsing the client request -> execute business logic -> output response page to the client

II.service () method thread

     To improve efficiency, a Servlet examples Servlet specifications must be able to service requests to a plurality of clients, i.e. service () method operating in a multithreaded environment, the developer Servlet must ensure thread safety of the process.

III.service () method with the exception

     service () method in the process execution and can throw ServletException IOException. Wherein ServletException can throw in processing client requests, such as requested resources are not available, the database is unavailable and the like. Once the exception is thrown, the container must be recovered request object, and report the abnormal message client. IOException represents the input and output of the error, the programmer does not have to be concerned about the exception, directly from the container can be reported to the client.

Programming Notes Description:

1) When the Server Thread thread init to perform Servlet instance () method, all of the Client Service Thread thread can perform the service of the instance () method, and no thread can execute destroy the instance () method, so the Servlet's init () method works in a single-threaded environment, developers do not have to consider any thread safety issues.

2) When the server receives a plurality of requests from clients, the server performs the service Servlet instance in a separate thread Client Service Thread () services to each client. At this time, there will be multiple threads execute the same Servlet examples of service () method, it is necessary to consider thread safety issues.

3) Please note that although this method service () method runs in a multithreaded environment, not necessarily in sync. But this method depends on the type of resource accessed during execution and access to resources the way. analyse as below:

     i. If the service () method does not access the Servlet member variables and no access to global resources such as static variables, files, database connections, but only the current thread's own resources, such as non-temporary variables point to global resources, request and response objects. The method itself is thread-safe, without making any synchronization control.

      ii. If the service () method to access the Servlet member variables, but the operation of the variable is read-only operations, which itself is thread-safe, without making any synchronization control.

      iii. If the service () method to access the Servlet member variables, and operations on the variables have both read write, usually need to add synchronization control statement.

      iv. If the service () method to access a global static variable, if the same time the system may also have other threads to access the static variable, if there are both read write operations, usually need to add synchronization control statement.

      v. If the service () method to access global resources, such as files, database connections, usually need to add synchronization control statement.

4. termination of service

  When a container is detected Servlet examples should be removed from service when the vessel will call destroy the instance () method, so that the instances can release the resources it uses, saving data to persistent storage. When the memory need to release or close the container, the container will call instance Servlet destroy () method. After the destroy () method is called, will be released this Servlet container instance, which will then be recovered by the Java garbage collector. If you need to request again the Servlet handling, Servlet container creates a new instance of the Servlet.

  Throughout the Servlet life cycle, create a Servlet instance, call the instance's init () and destroy () method only once , when the initialization is complete, the instance of Servlet containers will be stored in memory by calling its service () method, the received service request.

. 2,019,612 that day after Vigor car colleagues sitting in a car accident fracture of another major event: the first time in four years, contacted the SGD brother.

 

Guess you like

Origin blog.csdn.net/xuwei_net/article/details/91491882