Java interview 2021, Tomcat's immortality - Embedded

Author: Mr. King of Xiangxue classroom

Reprint, please state the source!

preface

Tomcat is a very popular web server for deploying and running Java Web applications. Generally, we run our own web applications on a separate Tomcat instance. In fact, compared with this classic scheme, we can directly integrate the server runtime into the application, which is more flexible and convenient.

Maven dependency of embedded Tomcat

To use embedded Tomcat and package its runtime with Java Web applications, in Maven's POM Add the following dependencies to the XML file

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
    <version>${tomcat.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <version>${tomcat.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-logging-juli</artifactId>
    <version>${tomcat.version}</version>
</dependency>

Including Tomcat Version is an attribute that points to the actual version of Tomcat

<properties>
    <tomcat.version>8.0.48</tomcat.version>
</properties>

Tomcat embedded instance

The core class is org apache. catalina. startup. Tomcat

For example, the following code creates and starts an embedded Tomcat instance running on port number 8082

package com.xiangxue.embedded;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

public class EmbeddedTomcatEx {

    public static void main(String[] args) throws LifecycleException,
            InterruptedException, ServletException {

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8082);

        Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath());

        Tomcat.addServlet(ctx, "Embedded", new HttpServlet() {
            @Override
            protected void service(HttpServletRequest req, HttpServletResponse resp) 
                    throws ServletException, IOException {
                
                Writer w = resp.getWriter();
                w.write("Embedded Tomcat servlet.\n");
                w.flush();
                w.close();
            }
        });

        ctx.addServletMapping("/*", "Embedded");

        tomcat.start();
        tomcat.getServer().await();
    }
}

Let's explain the function of the above code in sections below:

Tomcat tomcat = new Tomcat();
tomcat.setPort(8082);

Tomcat starts on port 8082

Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath());

Each application is mapped to a context. Using this addContext() method, we create a file that is not a JSP file and has no web XML file application. We use the root context path and the current working directory of the document library.

Tomcat.addServlet(ctx, "Embedded", new HttpServlet() {
            @Override
            protected void service(HttpServletRequest req, HttpServletResponse resp) 
                    throws ServletException, IOException {
                
                Writer w = resp.getWriter();
                w.write("Embedded Tomcat servlet.\n");
                w.flush();
                w.close();
            }
        });

The addServlet() method adds a new servlet. The servlet uses a stream to respond to some text.

 ctx.addServletMapping("/*", "Embedded");

Servlet mapping controls how to access a servlet named Embedded. For our example, any URL will eventually call our servlet.

tomcat.start();
tomcat.getServer().await();

Finally, the Tomcat server starts.

The server is listening on port 8082, so type the following URL in your Web browser:

http://localhost:8082/

You can see the corresponding effect

summary

Basically, we use embedded Tomcat for the following purposes:

1) Rapid unit testing of Web components such as Java components

Instead of starting / stopping the Tomcat server and opening the Web browser for manual unit testing, you can use embedded Tomcat to perform unit testing automatically.

2) Provide Java Web applications as stand-alone Java applications

End users can now run a JAR file that starts the embedded server hosting the Web application. There is no need to download and install Tomcat and manually deploy Web applications.

3) Better control of Tomcat

Integrated embedded server enables you to better control the server, control the server from code, and automatically perform the steps of self reservation.

And the popular SpringBoot architecture directly uses the Main method to start one, which is also implemented in the above way, but more embedded Tomcat related configurations and parameters are used in the implementation.

summary

We always like to visit the great gods of big factories, but in fact, the great gods are just mortals. Compared with rookie programmers, they spend a little more time. If you don't work hard, the gap will only become larger and larger.

The interview questions are more or less helpful for what you have to do next, but I hope you can summarize your shortcomings through the interview questions in order to improve your core technical competitiveness. Every interview experience is a literacy of your technology. The effect of re examination and summary after the interview is excellent! If you need this full version of the interview question notes, just give me a lot of support for this article.

Data collection method: free download here

To sum up their own shortcomings in order to improve their core technical competitiveness. Every interview experience is a literacy of your technology. The effect of re examination and summary after the interview is excellent! If you need this full version of the interview question notes, just give me a lot of support for this article.

Data collection method: free download here

Keywords: Java Interview Programmer

Added by youknowho on Sat, 29 Jan 2022 12:29:19 +0200