preface


August 5th, fine, today’s sun is still exceptionally basked in.

Today is the third day of learning JavaWeb, learned a lot of….

Tomcat is very easy to use, you see, decompress this, go to bin, click startup.bat, and it runs

Servlet, simple, create a.java, inherit HttpServlet, rewrite methods, configure web.

So easy

Ninety percent? Ninety percent?


I admit it, I lost, I lost completely, and since I touched servlets the other day (I don’t know how many days) I’ve been thinking a hundred thousand whys

A Servlet may be simple to use and its code is understandable to me, but I don’t know what’s going on, so I keep wondering what a Servlet is and what it does….

Although the code can be typed out, but feel like walking on the cloud, soft, not practical.

Finally, with my constant efforts, I knew what a Servlet was

This article is not in-depth and lofty Tomcat, Servlet source code, for me this dish chicken is not realistic, this article is only to comb the nature of Tomcat, Servlet, only as a personal study notes


Tips: This article is a long one. I hope you can learn from it:

  1. The concept of web containers
  2. The basic architecture of Tomcat
  3. Configuration of Tomcat server. XML
  4. How Tomcat handles static resources
  5. Servlet Architecture (Servlet source Code Analysis)
  6. Actual use of servlets

The body of the

1. Web server & Web middleware & Web container

Before I dive into servlets, I think I need to understand the concept of a Web container and how it relates to a Web server.

  • Web server: Broadly speaking, a Web server is software or host that provides Web services, that is, web server software or a computer with Web server software installed.

    For example: IIS, Apache, nginx, etc

    A Web server can handle the HTTP protocol, respond to requests for static pages or images, jump to pages, or delegate dynamic requests to other programs

    So we can call IIS, Apache, Nginx, Tomcat, and so on Web servers because they all provide Web services.

  • Middleware: Software that provides the connection between system software and application software to facilitate communication among software components

    Middleware sits between the operating system and higher-level applications.

    It serves the function of isolating the application environment from the operating system so that application developers don’t have to worry about more system problems and focus directly on the application’s ability to solve them

    In short: Between the operating system and the applications we write, there should be an intermediary that allows us to focus more on the business logic of the application itself and less on the interaction with the operating system, or even the underlying stuff. Prefer Api usage

  • Container: A type of middleware that acts as a bridge between the operating system and applications

    Provide an environment for the application components in it, allowing the application to interact directly with the environment variables in the container without having to worry about other system issues.

  • Web container: a web server that complies with the JavaEE specification is called a web container in JavaEE. A container for processing Web services

    Example: Tomcat (Servlet container)

    Web container is used to provide an environment for application components (ASP, JSP) in it. It is a part of middleware, and it implements the parsing of dynamic languages. For example, Tomcat can parse JSPS because it has a Servlet container inside it

In short:

Web server: Can provide services to the outside world (static resources, dynamic resources)

Middleware: Software that helps applications interact with the system

Web container: middleware that helps applications (the JavaWeb programs we wrote) interact with the system and comply with the JavaEE specification standards

The relationship among the three is Web server > Web Middleware > Web container

2. Tomcat

Tomcat server is an open source lightweight Web application server. It is widely used in small and medium-sized systems and small concurrency situations. It is the first choice for developing and debugging Servlet and JSP programs.

I think this is the first sentence of most online articles about Tomcat, Me too πŸ˜‚

I copied it, too

The role of the server is not described here, let’s go straight to the skeleton, Tomcat architecture

Tomcat 2.1 principle

  • First, let’s take a look at the real thing: the Tomcat directory

  • Then there is the invisible, invisible, logical: Tomcat structure diagram

When looking at the Tomcat structure diagram, it is recommended to open your Tomcat directory and find the server.xml configuration file in conf

  • A server.xml configuration file is shown below:


πŸ… Tomcat components include Server, Service, and Connector

The Container is the core of Tomcat.

A Container is combined with one or more connectors and other supported components to form a Service. A Service can provide external capabilities. However, an environment is required for a Service to survive. This environment is the Server. The Server component provides the living environment for the normal use of Service services. The Server component can manage one or more services at the same time.

Tomcat has two main components

  • Connector


    πŸ“Œ A Connector listens for client requests on a specified port, receives TCP connection requests from the browser (connection-oriented), and creates a Request and Response object to exchange data with the requestor.

    πŸ“Œ then generates a thread to process the Request and pass the resulting Request and Response objects to the processing Engine(part of the Container), which gets the Response from the Engine and returns it to the requester.

    πŸ“Œ Tomcat has two classic connectors:

    One listens directly for HTTP requests from Browser; Another request comes from another WebServer.

    The HTTP/1.1 Connector listens on port 8080 for HTTP requests from the client Browser. The AJP/1.3 Connector listens for Servlet/JSP requests from other Web servers (other HTTP servers) at port 8009.


    The most important function of ❗Connector is to receive a connection request and assign a thread to the Container to handle the request. Therefore, it must be multithreaded. Multithreaded processing is the core of Connector design.

  • Container


πŸ“Œ Container is the parent interface of a Container. The Container is designed using a typical responsibility chain design pattern. It consists of four child Container components: **Engine, Host, Context, and Wrapper. ** These four components are responsible relationships, and there are containment relationships.

πŸ“Œ Usually one Servlet class corresponds to one Wrapper. If there are multiple servlets defining multiple wrappers, multiple wrappers should define a higher Container, such as Context

πŸ“Œ Context can be defined in the parent container Host. Host is not required, but you must use Host to run the war program, because there must be a web. XML file in the war. If you have multiple hosts, you define a top container Engine, which has no parent, so an Engine represents a complete Servlet Engine


  • Engine container

    The Engine container is relatively simple and only defines some basic associations

  • The Host container

    A Host is a subcontainer of Engine. A Host in Engine represents a virtual Host that runs multiple applications, installs and expands them, and identifies them so that they can be distinguished. Its child container is usually the Context, which in addition to associating the child container, also holds the information that a host should have.

  • The Context container

    Context represents the Context of the Servlet, which has the basic environment for the Servlet to run. In theory, a Servlet can run as long as there is a Context. Simple Tomcat can do without Engine and Host. One of the most important functions of a Context is to manage its Servlet instances. Servlet instances appear in a Wrapper inside the Context. How does the Context find the right Servlet to execute it? Tomcat5 used to be managed through a Mapper class. After Tomcat5, this function was moved to Request. As you can see from the previous sequence diagram, fetching subcontainers is allocated through Request.

  • Wrapper container

    Wrapper represents a Servlet that manages a Servlet, including its loading, initialization, execution, and resource recycling. Wrapper is the lowest level container, it has no children, so calling its addChild will report an error.

    The Wrapper implementation class is StandardWrapper, which also implements a ServletConfig with a Servlet initialization message, This shows that StandardWrapper will work directly with the various messages of servlets.

Other components

Tomcat also has other important components, such as the security component, logger log component, session, MBeans, naming and other components. Together, these components provide the necessary services for the Connector and Container.

2.2 Configuring Tomcat server.xml

Now that we have a general overview of Tomcat’s architecture, let’s take a look at the structure of Tomcat based on server.xml


The configuration structure in the XML file corresponds to the architecture of Tomcat

  • The root directory is

    , which represents the Server, and under

    there is a

    , which represents the Service.


    A Service wraps Executor, Connector, and Engine to form a complete Service

  • There are two < connectors > under

    that represent connections (additional if necessary)

    Connector is Tomcat’s entry point for receiving requests, and each Connector has its own listening port

    • The HTTP/1.1 Connector listens on port 8080 for HTTP requests from the client Browser.
    • The AJP/1.3 Connector listens for Servlet/JSP requests from other Web servers (other HTTP servers) at port 8009.
  • Parallel to Connector is the

    (also known as the Servlet Engine above).

    Engine handles all requests within a Service.

    It receives a request from the Connector and decides which Host to send to process the request. When the Host processes the request, it returns the result to the Engine, which in turn returns the result to the Connector

  • Engine has a

    under it, which represents a Host

    Host is responsible for managing one or more Web projects


  • represents a Web project running on Host

    You can have multiple contexts on a Host. To add a Web project (D:\MyApp) to Tomcat, add the Context tag to the Host tag: <Context path=”” docBase=”D:\MyApp” reloadable=”true” crossContext=”true”>

The above is only a brief overview of the server.xml configuration. For details, please refer to server.xml configuration


server.xml


      
<! The configuration structure in the server.xml file corresponds to the Tomcat architecture. The root directory is <Server>, which represents the Server -->
<Server port="8005" shutdown="SHUTDOWN">
    <! -- Listener is a Listener that listens for specific events -->
    <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
    <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on"/>
    <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
    <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

    <! -- GlobalNamingResources for configuring JNDI -->
    <GlobalNamingResources>
        <Resource name="UserDatabase"
                  auth="Container"
                  type="org.apache.catalina.UserDatabase"
                  description="User database that can be updated and saved"
                  factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                  pathname="conf/tomcat-users.xml"/>
    </GlobalNamingResources>

    <! -- <Server> There is only one <Service> under the <Server>, which represents the Service. A Service wraps Executor, Connector, and Engine to form a complete Service.
    <Service name="Catalina">
        <! Executor is a thread pool provided by a Service and used by the components of the Service.
        <! <Executor name="Super Super black "namePrefix=" Super Super black "/>-->

        <! HTTP Connector and AJP Connector Tomcat is configured with two ports by default: One is the HTTP/1.1 protocol === that handles HTTP requests. One is that the AJP/1.3 protocol === listens for Servlet/JSP requests from other Web servers (other HTTP servers). Connector listens on the port and forwards requests to Engine -->

        <! -- Handle HTTP requests -->
        <Connector port="8080"
                   protocol="HTTP / 1.1"
                   connectionTimeout="20000"
                   redirectPort="8443"/>

        <! Listen for Servlet/JSP requests from other Web servers (other HTTP servers) -->
        <Connector port="8009"
                   protocol="AJP / 1.3"
                   redirectPort="8443"/>

        <! Engine handles all requests within a Service. It receives a request from the Connector and decides which Host to send it to. When the Host processes the request, it returns the result to Engine, which in turn returns the result to Connector.
        <Engine name="Catalina" defaultHost="localhost">
            <Realm className="org.apache.catalina.realm.LockOutRealm">
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                       resourceName="UserDatabase"/>
            </Realm>

            <! -- Host manages one or more Web projects -->
            <Host name="localhost"
                  appBase="webapps"
                  unpackWARs="true"
                  autoDeploy="true">

                <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
                       prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t &quot;%r&quot; %s %b"/>
                <! -- Context represents a Web project running on Host configuration virtual directory PATH: access resource URI. URI names can be arbitrary, but must be preceded by/docBase: You are advised to configure the virtual directory as an XML file in conf\Catalina\localhost, which is less intrusive to the Tomcat root configuration file. To delete the configured virtual directory, delete the configuration file.
                <! --<Context path="/ttt" docBase="test"/>-->
            </Host>

            <! -- Configure virtual host -->
            <! --<Host name="www.myweb.cn" appBase="f:/myweb" unpackWARs="true" autoDeploy="true"> <Context path="/" docBase="web"/> </Host>-->
        </Engine>
    </Service>
</Server>
Copy the code

2.3 An Http request Process


Tomcat Server processes an HTTP request

  1. The client sends the request (refresh the page, click the button) and the request is sent to native port 8080, picked up by the Coyote HTTP/1.1 Connector listening there;

  2. Connector passes the request to the Engine of its Service for processing and waits for the Engine to respond.

  3. Engine gets request localhost/test/index.jsp, matching all virtual Host hosts;

  4. The Engine matches a Host named localhost (if not, the request is processed to that Host because it is defined as the default Host for the Engine);

  5. The Host named localhost gets the request /test/index.jsp and matches all the contexts it owns.

  6. Host matches the Context whose path is /test (if not, pass the request to Context whose path name is “”);

  7. The path=”/test” Context gets the request “/index.jsp” and finds the corresponding Servlet in its mapping table.

  8. Context matches the Servlet of <url-pattern>*.jsp</url-pattern>, corresponding to the JspServlet class

    • Servlets that can handle JSPS (tomcat/conf/web.xml) :
  • Mapping of the Servlet (tomcat/conf/web.xml) :
  1. Construct HttpServletRequest object and HttpSerletReasponse object, as parameters, call JspServlet doGet() or doPost() to perform business logic, data storage, etc.;
  2. Context returns the HttpServletResponse object to Host after execution;
  3. Host returns the HttpServletResponse object to an Engine;
  4. Engine returns the HttpServletResponse object to Connector;
  5. The Connector returns the HttpServletResponse object to the client Browser.

2.4 Tomcat Processes static Resources

Tomcat’s handling of static resources can be summarized in one sentence:

Requests in Tomcat are handled by servlets and static resources are no exception.


Maybe we’re used to opening Tomcat, deploying an application, and then checking the results, or paying more attention to whether the logic in the Servlet is correct. As for static resource handling, I haven’t paid any attention to it.

Essentially, Tomcat does the same thing for all static resources. That is, in all the places where you don’t configure URL matching (there is no corresponding Servlet), Tomcat’s globally homogeneous configuration takes over.

For the configuration of the global same processing, it is in the conf directory of Tomcat. There is a web.xml. After opening it, you can search globally: DefaultServlet.

How, see here is familiar, it is a Servlet declaration, the Servlet statement to the associated Servlet class is org. Apache. Catalina. Servlets. DefaultServlet this class

It also has an initialization parameter called listings, which defaults to false.

This parameter controls whether files in the application directory are allowed to be displayed in lists when no welcome files are available. If set to true, a common FTP server will list all files in the application directory, as shown below. Of course, this style is also self-definable.

Look further down:

The mapping url for the default Servlet is /

If url-pattern is set to /, it should respond to all requests.

That’s right, as we mentioned above, is to match all servlet-mapping requests that you didn’t define.

The reason why self-defined servlets take effect preferentially is that the Servlet configuration in Tomcat is initialized strictly in the declared order and responds to requests in this order. Layer by layer comparison, if one can respond to requests, it will be used for processing.

If you are interested can look at org. Apache. Catalina. Servlets. DefaultServlet source code

3. Servlet

All right, here comes the star of the day

3.1 the Servlet calls

Not so fast, but have you noticed recently that we haven’t written a main method in a long time, and I’m sure we’ll do the same in the future.

We no longer care, or even know, who called the program I wrote. Anyway, I wrote a class that was never even new, and it just ran…

In fact, all of this is simply “injection” and “callback”.

There is a mian method in Tomcat. Suppose it looks like this:

In general terms, the Servlet class we wrote gets called in a snap of Tomcat and performs the desired logic

By the time you get to this point, have you somehow figured out what a Servlet is

3.2 Tomcat is full of servlets

We know that requests in Tomcat are handled by servlets

  • Static resources are handled by DefaultServlet
  • Jsp is handled by JSPServlets
  • There are other servlets that we define ourselves

Servlets are roughly divided as follows:

3.3 What exactly is a Servlet

The role and position of servlets

When we develop JavaWeb, we always need a web server to deploy our projects, both in development and in production.

Let’s take lightweight Tomcat as a “server,” in fact

Tomcat server = Web server + Web container

Tomcat receives a request as follows:


The Connector component listens for the necessary port (8080), and when the request is received, the Connector component creates two objects:

  • Request: Intercepts various information in the request and encapsulates it into an object
  • Response: Empty object

These two objects are then passed to the Container component, which is the other core component in Tomcat

Engine > Host > Context > Wrapper(Servlet)

Container takes the request, passes the two objects layer by layer, and finally arrives at the Servlet, which handles the request (logical processing)

When the Servlet completes processing, it puts the result into the response and passes it up the hierarchy to the Connector and back to the client


From all of the above we know:

  • Servlets are the last layer in the Tomcat architecture
  • Servlets are used to process requests and return the results of processing

So what exactly is a Servlet?

It starts with JAVA EE, which is a set of standards based on JAVA technology.

On the other side of the ocean in the 1990s, a company called SUN created a new language called Java.

After just a few years of development, it has become the hottest language on the market.

Then came the “Java13 stunt,” the so-called JavaEE specification:

JDBC, JNDI, EJB, RMI, JSP, Servlets, XML, JMS, Java IDL, JTS, JTA, JavaMail, JAF.

See, servlets are a specification in JavaEE

The answer is as follows:

Serlvet is a technology in Java, and JavaEE defines the specification for this technology, and only one specification

What is the purpose of the specification, is it to realize the function, so someone produces a product according to the specification, we want to use someone else’s product, we have to operate according to the specification (instructions), can play the role of the product

The purpose of this product is to process the request and return the result

This “product” is actually a Servlet container

The Servlet container, however, is present in Tomcat and, of course, in other places (server software)

Summarizing what a Servlet is

  • Servlets are a specification in JavaEE
  • Specification alone is not enough, there needs to be a concrete implementation, namely a Servlet product
  • We can use the Servlet product with the Servlet specification we are familiar with
  • Processing of requests is possible through the use of Servlet products
  • The Servlet product in each Web server is called a Web container (Servlet container)

4. Use the Servlet

Well, after all this preparation, it’s time to finally see the Servlet. If you can read the whole article and understand it, I can tell you that the Servlet is πŸ’¨πŸ’¨πŸ’¨

Let’s take the FIG leaf out of servlets

4.1 interface Servlet

In code, a Servlet is simply an interface

So so

Yes, you read that right, there are only five methods in this interface

Five methods, the hardest part is the parameter object, but Tomcat will wrap the parameter object and pass it to us. Besides, we don’t need to write TCP connection to the database, we don’t need to parse the HTTP request, and we don’t need to convert the result into an HTTP response. The Request object and the Response object helped me

Do you remember the two objects that were created when the Connector received the request, request and Response, and then passed down one layer at a time?

In this way, the Servlet implementation class is really just a shell, you just have to rewrite its methods, put logic code in it, and Tomcat executes itself.

So easy

4.2 Three parameters in the Servlet interface

  • ServletConfig: As the name implies, “Servlet configuration”

    Recall where we configured the Servlet? Is it in web.xml

    In fact, the ServletConfig is the configuration item written in web.xml that Tomcat parses, encapsulates, and passes to us as a Servlet object

  • Request/Response

    Simple, request object/response object

    When and how these two objects were created was highlighted earlier, so we won’t go into details here

4.3 GenericServlet

When we pull the FIG leaf off the Servlet, it’s so simple

But it’s an interface, and if we were to create the Servlet each time by implementing the Interface Servlet, we would have to rewrite all the methods in it every time. Maybe that’s not what we want. We might just want to use the Service method every time. Simply processing the request will do

Is it too redundant to implement the Interface Servlet

Don’t worry, Java also provides another way to create a Servlet by inheriting GenericServlet

Take a look at our implementation code:

package com.itheima.servlet;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class ExtendsGenericServlet extends GenericServlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {}}Copy the code

Is it that we just overwrite a service method and that’s it

Let’s see who this GenericServlet is

This is an abstract class that implements the Servlet interface:

We found that GenericServlet made a few improvements:

  • Improved the scope (local variables -> member variables) of the ServletConfig object that was originally a parameter in the init method to make it easier for other methods to use
  • The init method also calls an init null parameter construct. If we want to do some initialization during Servlet creation, we can inherit GenericServlet and override the init null parameter construct
  • Since ServletConfig can be used in other methods, we write a getServletContext method

As a result, GenericServlet simplifies our creation process (just overriding the Service method)

However, there are many kinds of request methods, so when we actually process the request through the service method, we often have to determine the request method (for example: determine the current request is GET/POST/PUT /delete…).

That’s a lot of redundant code for us

Don’t worry, and…

4.4 the HttpServlet

The HttpServlet class abstraction

The HttpServlet structure


You can see that HttpServlet inherits from GenericServlet

Looking at the source code, you can see that the HttpServlet already implements the Service method

In short: The Service method of HttpServlet has done the complex request judgment for us

Ok, now it’s even easier, we just need to override doGet/doPost/doPut in a derived class of HttpServlet… These methods will do

Something like this:

public class ExtendsHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        / /...

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        / /...}}Copy the code

OK, servlets are so simple

Ninety percent? Ninety percent? Ninety percent? Ninety percent? Ninety percent? Ninety percent? Ninety percent? Ninety percent? Ninety percent?

The reference to

Thanks to invade delete

The difference between Web servers, Web middleware, and Web containers

Tomcat gaiden

Tomcat (I) : Introduction

Tomcat (2) :server. XML configuration

How does Tomcat respond to static resources?

Tomcat handling of static resources

Will access to static resources in Tomcat also be handled with servlets?

What is the nature of servlets and how does it work?