As a core project of the Apache Software Foundation Jakarta project, Tomcat is favored by Java enthusiasts and recognized by some software developers due to its advanced technology, stable performance and free, making it a popular Web application server. Next, I will share my understanding of Tomcat with you, hoping to help you.

http://localhost:8080/ resource path to access project resources. In this process, Tomcat plays the role of the scheduling center, receives and parses resource requests initiated by browsers, distributes the results to specific Web projects for processing, and then responds to browsers based on the processing results. Let’s take a look at how Tomcat does this.

MyTomcat To receive requests initiated by browsing, you need to perform several preparations: 1: listening port (8080), 2: receiving browser connection (socket connection), 3: parsing HTTP Request data. Here is the code simulation:

Step 1 and step 2: /** * public class httpServer {// Tomcat project absolute path, Public static final String WEB_ROOT = system.getProperty (public static final String WEB_ROOT = system.getProperty ("user.dir") + File.separator  + "webapps"; // Simulate tomcat shutdown command private static final String SHUTDOWN_CMD ="/SHUTDOWN";
    private boolean shutdown = false; // Continue listening port @suppressWarnings ("resource")
    public void accept() { ServerSocket serverSocket = null; ServerSocket = new serverSocket (8080, 1, inetAddress.getByName ("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to start myTomcat server:"+ e.getMessage(), e); } // Listen until a close command is receivedwhile(! shutdown) { Socket socket = null; InputStreamin= null; OutputStream out = null; Socket = serversocket.accept ();in= socket.getInputStream(); out = socket.getOutputStream(); Request Request = new Request(in); request.parseRequest(); Response Response = new Response(out); Response.sendredircet (request.geturi ()); socket.close(); // If the shutdown command is used, stop listening and exit shutdown = request.geturi ().equals(SHUTDOWN_CMD); } catch (Exception e) { e.printStackTrace();continue; } } } public static void main(String[] args) { new HttpServer().accept(); /** * public class Request {// Private InputStream for socket connectionsin; Private String URI; public Request(InputStreamin) {
        this.in = in; } // Parse browser requests public voidparseRequestByte [] buff = new byte[2048]; StringBuffer sb = new StringBuffer(2048); int len = 0; // Try {len = in.read(buff); sb.append(new String(buff, 0, len)); } catch (IOException e) { e.printStackTrace(); } System.out.print(sb.toString()); Uri = this.parseuri (sb.tostring ()); } /** Tomcat uses HTTP to receive requests from browsers. The request content is in the following format: */ /** Request line: Request mode Request URI Protocol version */ //GET /index HTTP/1.1 /** Request header: */ /Host: localhost:8080 //Connection: keep-alive // upgrade-insecure -Requests: 1 // user-agent: //Host: localhost:8080 //Connection: keep-alive // upgrade-insecure -Requests: 1 // user-agent: Mozilla / 5.0... //Accept: text/html,application/xhtml+xml...... //Accept-Encoding: gzip, deflate, br //Accept-Language: zh-CN,zh; Q = 0.9 / / cookies:... Public String parseUri(String httpContent) {public String parseUri(String httpContent) { Request Mode Request URI Protocol Version Three items separated by Spaces int beginIndex = httpContent.indexof ("");
        int endIndex;
        if(beginIndex > -1) {
            endIndex = httpContent.indexOf("", beginIndex + 1);
            if(endIndex > beginIndex) {
                returnhttpContent.substring(beginIndex, endIndex).trim(); }}return null;
    }

    public String getUri() {
        returnuri; Initiate the request}} hypothesis, the browser: http://localhost:8080/hello/index.html HttpServer socket in obtain the data from the input stream is: GET /hello/index.html HTTP/1.1 Host: localhost:8080 Connection: keep-alive upset-insecure -Requests: 1 user-agent: Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp image/apng, * / *; Q =0.8 Accept-encoding: gzip, deflate, BR Accept-language: zh-cn,zh; Q = 0.9 cookies: Hm_lvt_aa5c701f4f646931bf78b6f40b234ef5 = 1516445118151604, 544151416, 964151497, 222; JSESSIONID = 79367 fd9a55b9b442c4ed112d10fdac5 HttpServer will be treated as the data exchange in the HttpRequest object, the object call parseRequest parsing, get request uri of the data, analysis of the data, Get the context path, project name, and resource name. Resource paths. The above data can be obtained: In the hello item, the index. HTML resource (no context path) responds to the request. After retrieving the URI from the request information and then retrieving the hello item, the index. HTML resource, you can simply respond to the request by looking for the resource based on the resource path. Use socket Output stream to output resource data directly, if not found, output 404 information. Public class Response {private OutputStream out; public Response(OutputStream out) { this.out = out; } public OutputStreamgetOutputStream() {
        returnout; } // skip public void webPage (String uri) {File webPage = new File(httpserver. WEB_ROOT, uri); FileInputStream fis = null; StringBuffer sb = new StringBuffer(); Try {// Find the page isif(webPage.exists()&& webPage.isFile()) {
                String respHeader = "HTTP / 1.1 200 OK \ r \ n" +
                  "Content-Type: text/html\r\n" +
                  "Content-Length: #{count}\r\n" +
                  "\r\n";
                fis = new FileInputStream(webPage);
                byte[] buff = new byte[2048];
                int len = 0;
                while( (len = fis.read(buff))! = -1) { sb.append(new String(buff, 0, len)); } respHeader=respHeader.replace("#{count}", sb.length()+"");
                System.out.println(respHeader + sb);
                out.write((respHeader + sb).getBytes());
                
            }elseString errorMessage = if the page is not found"HTTP/1.1 404 File Not Found\r\n" +
                  "Content-Type: text/html\r\n" +
                  "Content-Length: 23\r\n" +
                  "\r\n" +
                  "<h1>File Not Found</h1>";
                out.write(errorMessage.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fis ! = null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); }}}}Copy the code

Note here that the response request data must also follow the HTTP protocol. Of course, these contents are only part of Tomcat, if you want to continue to explore about Tomcat, you can continue to research or follow us, we will continue to publish relevant tutorials, and make progress together.