How Tomcat works Reading Notes 3 ------- Connector

Source: Internet
Author: User
Several Concepts: httpservlet and Servlet
Servlet is an interface that defines a network service. All our servlets need to implement it (or its subclass)
Httpservlet is an abstract class that targets HTTP network services.
Of course, if you have other network services in the future, you can define another class to implement servlet.
Httpservletrequest, servletrequest
Let's talk about the servletrequest interface, which is used to transmit network service requests and is used in servlet-class service methods.
Therefore, the httpservletrequest interface mainly targets HTTP requests.
Httpservletrequest has more methods for HTTP than servletrequest. Such as getheader, getmethod, and getsession.

For a large system, stringmanager must handle error messages with caution. If you save all the error messages in a properties file, it will be extremely complicated, therefore, Tomcat creates a set of properties files for each package in the system (a group rather than a group to support multi-language localstrings. properties, localstrings_es.properties, localstrings_ja.properties are English, Spanish, and Japanese)


For example, in the httpprocessor class under the ex03.pyrmont. connector. http package, we reference stringmanager as follows:
Protected stringmanager Sm =
Stringmanager. getmanager ("ex03.pyrmont. connector. http ");
Used where an exception is to be thrown
Throw new servletexception
(Sm. getstring ("httpprocessor. parseheaders. colon "));
Now let's take a look at the properties file (partial) under the httpprocessor. parseheaders. Colon package)
Httpprocessor. parseheaders. Colon = invalid HTTP Header Format
Httpprocessor. Starting = starting background thread
Httpprocessor. Stopping = stopping background thread
Requeststream. Close. Closed = request stream has already been closed
Now we know the stringmanager function.

In addition, the generation of stringmanager is a singleton mode. You can refer to the source code.


In this chapter, the HTTP request object is represented by httprequst (this class does not exist in JDK). It implements the httpservletrequest interface.
When used, httprequst is transformed into httpservletrequest and called as a parameter of the servlet service method.
Therefore, we need to set the member variables of each httprequest instance for the servlet instance. The values to be set include Uri, query string, parameter, Cookie, etc.
Therefore, there is a problem here. parsing the HTTP Request body (note that the get/POST Request Method and the request header will all be parsed) involves many string operations, if we only parse the values that will be used, we can save a lot of CPU cycles.
So only when we call javax. servlet. HTTP. getparameter (), getparametermap (), getparameter-names (), and getparametervalues () of httpservletrequest will only parse the Request body (and only parse the four methods that are called multiple times )!
The specific method is to call a parseparameters () method in the first line of code in the above four methods in the httprequest class (the one we wrote implementing the httpservletrequest interface. Parsed ensures that parseparameters runs only once.
(In addition, I think the request string should be part of the Request body)

Chapter 2 helps us build a simple servlet container that can load static resources and process some simple servlets. In this chapter, we need to further improve our container so that it can obtain some parameters of the Request request.
Therefore, the servlet in this section will inherit httpservlet, And the passed parameter will also be httpservletrequest.


Application code

The servlet code in this chapter is as follows:

Import javax. servlet. *; import javax. servlet. HTTP. *; import Java. io. *; import Java. util. *; public class modernservlet extends httpservlet {public void Init (servletconfig config) {system. out. println ("modernservlet -- init");} public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html"); printwriter out = response. getwriter (); out. println ("<HTML>"); out. println ("


First look at the UML diagram


The system extracts a bootstrap class, loads the httpconnector class, and calls its start () method.

package ex03.pyrmont.connector.http;import java.io.IOException;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;public class HttpConnector implements Runnable {  boolean stopped;  private String scheme = "http";  public String getScheme() {    return scheme;  }  public void run() {    ServerSocket serverSocket = null;    int port = 8080;    try {      serverSocket =  new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));    }    catch (IOException e) {      e.printStackTrace();      System.exit(1);    }    while (!stopped) {      // Accept the next incoming connection from the server socket      Socket socket = null;      try {        socket = serverSocket.accept();      }      catch (Exception e) {        continue;      }      // Hand this socket off to an HttpProcessor      HttpProcessor processor = new HttpProcessor(this);      processor.process(socket);    }  }  public void start() {    Thread thread = new Thread(this);    thread.start();  }}


The run method of httpconnector is similar to httpserver1 in Chapter 1 of the book, but after obtaining inputstream in chapter 1, let him generate a request. Here, we create httpprocessor, and call its process method to convert serversocket. accept () socket input.
The process method of httpprocessor is as follows:

public void process(Socket socket) {SocketInputStream input = null;    OutputStream output = null;    try {      input = new SocketInputStream(socket.getInputStream(), 2048);      output = socket.getOutputStream();      // create HttpRequest object and parse      request = new HttpRequest(input);      // create HttpResponse object      response = new HttpResponse(output);      response.setRequest(request);      response.setHeader("Server", "Pyrmont Servlet Container  ***");      parseRequest(input, output);      parseHeaders(input);      //check if this is a request for a servlet or a static resource      //a request for a servlet begins with "/servlet/"      if (request.getRequestURI().startsWith("/servlet/")) {        ServletProcessor processor = new ServletProcessor();        processor.process(request, response);      }      else {        StaticResourceProcessor processor = new StaticResourceProcessor();        processor.process(request, response);      }      // Close the socket      socket.close();      // no shutdown for this application    }    catch (Exception e) {      e.printStackTrace();    }  }


Check this line of code

Input = new socketinputstream (socket. Fig (), 2048 );
Socketinputstream is a packaging class that implements the inputstream interface. We use socketinputstream to use its readrequestline () method readheader method. The former can read the request method, Uri and request protocol, and the latter can read the request header.

Build httprequest

Parserequest (input, output );
Parseheaders (input );
These two methods are the core of the process method, or the core of Chapter 3. To put it simply, the two methods are used to parse HTTP requests and fill in the httprequst object. Of course, there are many details here.
This section is simple and easy to explain. It is also difficult to explain. It is generally five parts.
1. Read the input stream of the socket.
Is the following line of code
Input = new socketinputstream (socket. Fig (), 2048 );
If you are interested, you can check the source code of readrequestline.
2. parse the request line (that is, the first line of the HTTP request includes the Request Method URI Protocol version)
3. parse the Request Header
4. parse cookies
5. Obtain parameters (the lazy load mentioned above)

Build httpresponse
In the servletresponse In chapter 2, we only implement some functions, and the print method cannot be automatically refreshed.
  public PrintWriter getWriter() throws IOException {    // autoflush is true, println() will flush,    // but print() will not.    writer = new PrintWriter(output, true);    return writer;  }

Through the code in the second chapter above, we know that writer is an instance of the printwriter class.
1. In this chapter, we use responsewriter to construct a writer instance (responsewriter inherits from printwriter)
2. The output in Chapter 2 is an instance of the outputstream interface. In chapter 3, we replace it with responsestream (responsestream inherits servletoutputstream, while the latter implements the outputstream interface)
3 At the same time, an outputstreamwriter is also required as a bridge between responsewriter and responsestream.
The Code is as follows:
Public printwriter getwriter () throws ioexception {responsestream newstream = new responsestream (this); // This indicates httpresopnse newstream. setcommit (false); outputstreamwriter OSR = new outputstreamwriter (newstream, getcharacterencoding (); writer = new responsewriter (OSR); Return writer ;}


The static resource processor and Servlet processor are basically the same as those in the previous chapter.


References
Http://zhidao.baidu.com/link? Url = BGdS8iiz12FmAlVLsoGj6n3LwclvQ7rD-8GOJ6U8uguM8IGZrDUooTkjnySAInrMkqA6a7XofgNu4J3ynbOPC _






How Tomcat works Reading Notes 3 ------- Connector

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.