tomcat, servlet container, web container. . .

Reference article:

  1. What is the servlet container: https: //blog.csdn.net/yw_1207/article/details/78706701
  2. Understand the concept of Servlet and Servlet container, Web servers:
    https://blog.csdn.net/lz233333/article/details/68065749
  3. (Main) Servlet Source :
    https://blog.csdn.net/qq_19782019/article/details/80292110

1. What is a web server

Before understanding servlet container, you must first understand the web server

  1. Definitions: web server uses http protocol to transfer data. Server to complete the job is sent to the client web page, http protocol transmission process to follow, he pointed out the request (request) messages and responses (response) message format.

Here Insert Picture Description

Here we can find that rely on a web server, the client requests only static Web pages to the server, if the user wants to read pages based on their input, which is dynamic pages, is unable to meet, this time, we need to of the servlet container

For example tomcat:

Here Insert Picture Description

2. What is the servlet container

  1. Defined: also called Servlet container Servlet engine, part of the Web server or application server for providing network service requests and responses sent over the decoded MIME-based request, the MIME format based on the response. Servlet no main method, can not operate independently, it must be deployed to the Servlet container, the container is instantiated and invoked Servlet methods (e.g. doGet () and the doPost ()), Servlet container inclusion and managed within Servlet life cycle Servlet. After the introduction of JSP technology, management and operation of Servlet / JSP container, also known as Web container.

3. What is the servlet

  1. Definition: is written in Java Server-side program.Its main function is to interactively view and modify data, generate dynamic Web content. It 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. From the implementation speaking, Servlet response to any type of request, but only for the most part extend Servlet Web server based on HTTP protocol.

  2. Operating mode:
    The client sends a request to the server
    the server is up and call Servlet, Servlet response generated content for the client request to the server and
    the server returns the response client

  3. Servlet works

    Servlet interface definesServlet servlet container and betweenContract. This contract is: Servlet class Servlet container will be loaded into memory, and generates Servlet examples and call its specific method. However, to note that,In one application, each type can have only one instance of Servlet

    User requests resulting Servlet container calls the Servlet Service () method,And pass a ServletRequest object and a target ServletResponse. ServletRequest object and the objects are ServletResponse by the Servlet container (e.g. TomCat) packaged, the programmer does not need to be realized.

  4. ServletRequest, ServletResponse, ServletContext objects to explain

    ServletRequest encapsulates current Http request, and therefore, the developer does not have to parse and manipulate Http original data. ServletResponse Http response indicates that the current user's programmers to directly manipulate objects ServletResponse will be able to easily send a response back to the user.

    For each application, Servlet container also creates a ServletContext object. This object encapsulates details environmental context (application). Each application has only one ServletContext. Each object can also have a Servlet Servlet ServletConfig object configuration package.

Life cycle:

  1. init () is called in the initialization phase servlet lifecycle, passed javax.javax.servlet.ServletConfig an object that implements the interface, so that servlet initialization parameters can be acquired from the web application.
  2. Each servlet receives a request, it will call the service () method. Processing each request are performed in a separate thread, type (doget (), dopost ()) service () method of determining the request and sends it to the appropriate processing method.
  3. When you need to destroy servlet object, it calls the destroy () method to release the resources occupied.

How servlet container and a web server processes the request.

  1. http web server receives the request
  2. The web server forwards the request to the servlet container
  3. If desired servlet, the containers will retrieve the servlet, the container is loaded into the address space does not exist in the container.
  4. The container calls init servlet () method to initialize the servlet (the method is only called when the servlet is first loaded)
  5. The service servlet container calls () method to handle http request: read data request to create a response, servlet will be retained in the address space of the container, continues to process additional http requests
  6. web server dynamically generated results are returned to the correct address.

Here Insert Picture Description
Here Insert Picture Description

How httpService subject to processing methods such as doget || dopost

First we look at the source code

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String method = req.getMethod();
    long lastModified;
    if (method.equals("GET")) {
        lastModified = this.getLastModified(req);
        if (lastModified == -1L) {
            this.doGet(req, resp);
        } else {
            long ifModifiedSince = req.getDateHeader("If-Modified-Since");
            if (ifModifiedSince < lastModified) {
                this.maybeSetLastModified(resp, lastModified);
                this.doGet(req, resp);
            } else {
                resp.setStatus(304);
            }
        }
    } else if (method.equals("HEAD")) {
        lastModified = this.getLastModified(req);
        this.maybeSetLastModified(resp, lastModified);
        this.doHead(req, resp);
    } else if (method.equals("POST")) {
        this.doPost(req, resp);
    } else if (method.equals("PUT")) {
        this.doPut(req, resp);
    } else if (method.equals("DELETE")) {
        this.doDelete(req, resp);
    } else if (method.equals("OPTIONS")) {
        this.doOptions(req, resp);
    } else if (method.equals("TRACE")) {
        this.doTrace(req, resp);
    } else {
        String errMsg = lStrings.getString("http.method_not_implemented");
        Object[] errArgs = new Object[]{method};
        errMsg = MessageFormat.format(errMsg, errArgs);
        resp.sendError(501, errMsg);
    }
}

Next we look at how the service is to work, we will find the service methods still do not have any service logic, but it == analytical method parameter in the HttpServletRequest and call one of the following methods: doGet, doPost, doHead, doPut, doTrace, doOptions and doDelete. == these seven methods, each method represents a method Http. doGet and doPost are most commonly used. So, if we need to implement specific service logic, no longer need to override the service method, and only need to cover doGet or doPost just fine.

总之,HttpServlet有两个特性是GenericServlet所不具备的:

1.不用覆盖service方法,而是覆盖doGet或者doPost方法。在少数情况,还会覆盖其他的5个方法。

2.使用的是HttpServletRequest和HttpServletResponse对象。

request garbled solution

In front of us talked, encoding and decoding method used in the service of the default: ISO-8859-1 encoding, but this encoding does not support Chinese, so there will be garbled, so we need to manually modify the encoding to UTF-8 encoding in order to solve the Chinese garbage problem, the following is garbled details:

Here Insert Picture Description

Solve the garbage post submission of: request.setCharacterEncoding ( "UTF-8");

The way to solve the garbage get submitted:

parameter = newString(parameter.getbytes(“iso8859-1”),“utf-8”);

Response garbage problem

Here Insert Picture Description
The reason: the default encoding response buffer is iso8859-1, this code table is not Chinese. So we need to change response encoding:
Here Insert Picture Description
by changing the response encoding to UTF-8, any course can not solve the garbage problem, because the sender server may have changed the encoding to UTF-8, but the receiving end browser still use GB2312 decoding encoding, or can not restore normal Chinese, and therefore also need to tell the browser to use UTF-8 encoding to decoding.

Here Insert Picture Description

上面通过调用两个方式分别改变服务端对于Response的编码方式以及浏览器的解码方式为同样的UTF-8编码来解决编码方式不一样发生乱码的问题。

response.setContentType ( "text / html; charset = UTF-8") This calling method includes two methods of the above, in the actual development thus, only need to call a response.setContentType ( "text / html; charset = UTF-8 ") method may be.

Here Insert Picture Description
Here Insert Picture Description

Response workflow

Here Insert Picture Description

http request connection

  1. http issues a connection request to the server
  2. New tcp connection
  3. The server sends a message http
  4. After the termination by the news server, it sends back an ack message, and then sendhtml follicles
  5. Browser reply to the corresponding ack packets,Html parsing code and resource requests (js, etc.)
  6. The server sends a response code
  7. Server closes the connection ()

Independent Servlet container

When we use the Web server based on Java technology, Servlet container as part of composing Web server exists. However, most Web servers not based on Java, and therefore, there is a mode of operation of two Servlet container.

2) Servlet container process
Servlet container by the implementation of two parts of the Web server plug-ins and Java containers. Web server plugin opens a JVM (Java Virtual Machine) in a Web server internal address space, so that the container can be loaded and run Java Servlet in this JVM. If the client calls the Servlet request comes, take control and plug this request pass it (using JNI technology) to the Java container, and then handed over by the Java Servlet container processing this request. Servlet container process for single-process, multi-threaded server is well suited to provide a high speed, but flexibility is inadequate.

3) Servlet container outside the process
Servlet container to run in the address space outside of the Web server, it is also achieved by the two parts of the Web server plug-ins and Java container composed. Web server plug-ins and Java container (running outside the JVM) use IPC mechanism (usually TCP / IP) to communicate. When a call Servlet request arrives, plug-in to take control of this request and passes it (using IPC mechanism) to the Java container. Process Servlet outer container in response to customer requests as fast as Servlet container process, but the outer container having better process stability and stretchability.

Related interview questions

1. The three modes of operation Tomcat Connector

https://blog.csdn.net/peerless_hero/article/details/53438808

1.1 bio (synchronous and blocks)

bio is a blocking operation io, tomcat default is to run in the bio.

On the understanding of "blocking", we recall await () method org.apache.catalina.core.Catalina class, after performing ServerSocket.accept () method Tomcat container would have been blocked to the client connection will not return .After each client connection over, the server will start a thread to handle the clientRequests.

I have two different page into the browser "localhost: 8005 / request1" and "localhost: 8005 / request2", console play the following information:

十二月 02, 2016 8:58:57 下午 org.apache.catalina.core.StandardServer await
警告: StandardServer.await: Invalid command 'GET /request1 HTTP/1.1' received
十二月 02, 2016 8:59:17 下午 org.apache.catalina.core.StandardServer await
警告: StandardServer.await: Invalid command '' received
十二月 02, 2016 8:59:33 下午 org.apache.catalina.core.StandardServer await
警告: StandardServer.await: Invalid command 'GET /request2 HTTP/1.1' received

bio will have the following disadvantages:
1. When a client for a long time, will createA large number of processing threads. Each thread stack space to be occupied and the number of CPU time.
2. obstruction may bringFrequent context switching, And most of the context switch is meaningless.
A general rule, bio mode is the lowest of three operating modes Properties of a.

1.2NIO (synchronous non-blocking)

  1. nio definitions: nio (non-blocking I / O) is a non-blocking I / O operations. nio is based buffer and a Java API provides non-blocking I / O operations, it has a better operating performance than the bio concurrent.

  2. How to modify nio: to let Tomcat nio mode to run is relatively simple, we only need to modify the server.xml file under:
    Here Insert Picture Description

NIO works include:

1. by a dedicated threadHandle all I / O events, and is responsible for distribution.
2. Event-driven mechanism, rather thanSynchronizeGround to monitor events.
3. communication between threads through == wait, notify == other ways. Ensure that each context switch is meaningful, reduce unnecessary thread switching.

NIO == using bidirectional channels (Channel) == for data transmission, instead of one-way flow (stream). We can register on the channel specified event, a total of four events:

1. The server receives the client connection event OP_ACCEPT (16)
2. The client terminal connection service event OP_CONNECT (. 8)
3. Read Event OP_READ (. 1)
4. Write Event OP_WRITE (4)

Service and clientEach maintain a management channel object, we call selector, The object can be detected in the event one or more channels. To the server, for example, if you register a reading event selector on the server, the client sends a certain time to the server some data, BIO will then call the read () method blocks read data, and the service will end at NIO adding selector in a reading event. Processing thread will poll the server to access the selector, find interesting events to reach the deal with these events if access selector; if there is no interest in reaching the event processing thread blocks until an event of interest arrives.

1.3APR (asynchronous non-blocking IO)

apr (Apache portable Run-time libraries / Apache Portable Runtime library) are Apache HTTP server support library. In apr mode, Tomcat will JNI (Java Native Interface) formCall the Apache HTTP Server core dynamic link libraryTo process the file transfer operation is a read or a network, thereby greatly improving the processing performance of the Tomcat static files. Tomcat apr is the preferred mode for highly concurrent applications running on Tomcat.

If you are not running under Tomcat apr mode, when you start Tomcat, we can see something like the following information in the log information:

十二月 02, 2016 8:24:09 下午 org.apache.catalina.core.AprLifecycleListener init
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: 

And let Tomcat run in apr mode

For the Tomcat 7.0.30 version to start back, only you need to modify the protocol again "org.apache.coyote.http11.Http11AprProtocol" can be. For previous versions of Tomcat 7.0.30, also need to support the following three components:
1.APR Library [the APR library]
2.JNI Wrappers for the APR Used by Tomcat (libtcnative) [named tcnative-1 on the Windows operating system the dynamic link library file .dll]
3.OpenSSL the libraries [OpenSSL library]

There are several ways to deploy Tomcat?

In the Tomcat Web application deployment we have the following main categories:

  1. Using the automatic deployment of Tomcat.

The web application (war file) copied to the webapps directory. Tomcat will load when you start the application directory, and compiled the results into the work directory.

  1. Use Manager App console deployment.

Click "Manager App" to enter the application management console tomcat home page, you can specify a path or web application war file.

  1. Modify conf / server.xml file deployment.

Modify conf / server.xml file, add the Context node can be deployed applications.

  1. Add custom Web deployment files.

Increase in conf / Catalina / localhost / path xyz.xml document, the content is Context node, the application can be deployed.

How tomcat servlet container class instance is created? What principle is used?

When the container starts, will read web.xml files for all web applications in the webapps directory, then xml file is parsed,And read the servlet registration information. Then, each application will be registered servlet class loading, and byReflection instantiate. (Sometimes also in the first instance of the request)
plus 1 if it is positive, then at the outset instantiated in the servlet registration, if you do not write or negative, the first request instantiated.

Tomcat top architecture Summary

Only a Tomcat Server, a Server can have multiple Service, a Service can have multiple Connector and a Container;

Server power of life and death in charge of the entire Tomcat;

Service is the external service provider;

Connector for receiving requests and packaged into Request and Response to a specific process;

Container for packaging and managing Servlet, and specific processing REQUEST request;

The role of 4 child container are:
Engine: Engine for managing multiple sites, a Service can only have a maximum of Engine;
Host: represents a site, can also be called a virtual host, by configuring the Host can add sites;
Context: It represents an application program corresponding to a normal development, or a WEB-INF directory and below web.xml file;
Wrapper: each encloses a Wrapper the Servlet;

Container how to process the request

Container processing request is to use Pipeline-Valve pipeline process! (Valve is a valve intended)

Pipeline-Valve is a chain of responsibility pattern, the chain of responsibility pattern refers to the process in the processing of a request handler in turn has a lot to process the request, each handler is responsible for doing their own appropriate treatment, the result of the process is returned after processing , let the next handler continues processing.

Published 36 original articles · won praise 11 · views 10000 +

Guess you like

Origin blog.csdn.net/s_xchenzejian/article/details/102790354