I. Overview

a brief introdction

  • Tomcat is a free and open source web application server, which is a lightweight application server.
  • It is commonly used in small and medium-sized systems and when there are not many concurrent users
    It is the first choice for developing and debugging JSP programs.
  • A core project in the Apache Software Foundation Jakarta project, developed by Apache, Sun, and some companies and individuals. It is loved by Java enthusiasts and recognized by some software developers. Compared with Apache or Nginx, the more popular web application server Tomcat has the function of processing HTML pages. However, because its ability to process static HTML is far less than that of Apache or Nginx, Tomcat is usually used as a Servlet and JSP container. Run alone on the back end.

Core components

  • Web container ------ completes the function of Web server.
  • Servlet container ------ named catalina, used to process Servlet code.
  • JSP container-used to translate JSP dynamic web pages into Servlet code.

JavaServlet

JavaServlet is a program that runs on a web server or application server. It acts as an intermediate layer between a request from a web browser or other HTTP client and a database or application on the HTTP server. Using Servlet, you can collect user input from web forms, present records from databases or other sources, and create web pages dynamically. Similar to CGI (Common Gateway Interface) function.

JSP container

  • JSP full name: Java Server Pages
  • It is a dynamic web development technology. It uses JSP tags to insert Java code in HTML pages. Tags usually start with <% and end with %>. JSP is a Java servlet, mainly used to implement the user interface part of a Java web application.
  • JSP obtains user input data through web forms, accesses databases and other data sources, and then dynamically creates web pages.

Tomcat top-level architecture

  • The topmost container in Tomcat is Server, which represents the entire server. A Server can contain at least one Service, which is used to provide specific services.
  • Service mainly consists of two parts: Connector and Container. The heart of Tomcat is these two components, the role of these two components: Connector is used to deal with connection-related things, and provide Socket and Request and Response related conversion; Container is used Encapsulates and manages Servlet, and specifically handles Request requests.
  • There is only one Server in a Tomcat, a Server can contain multiple Services, and a Service has only one Container, but there can be multiple Connectors, because a service can have multiple connections, such as providing Http and Https links at the same time, or providing the same direction The connection of different ports of the protocol.
  • Multiple Connectors and a Container form a Service. With Service, it can provide services to the outside world. However, Service also needs a living environment. Someone must be able to give her life and control her life and death. It is Server. Now! So the whole life cycle of Tomcat is controlled by Server. In addition, the above-mentioned containment relationship or parent-child relationship can be seen in the server.xml configuration file in the tomcat conf directory.
  • Defined in server.xml <Server port-"8005"shutdown-" SHUTDOWN">This will start Tomcat6--a server instance (ie-a JVM), it listens on port 8005 to receive the "SHUTDOWN" command, if it is received Tomcat will be shut down. Each Server
    The definition cannot use the same port, which means that if multiple Server instances are started on the same physical machine, they must be configured to use different ports.

The role of sub-containers

  • Engine: Engine, used to manage multiple sites, a Service can only have one Engine at most.
  • Host: Represents a site, which can also be called a virtual host. You can add a site by configuring Host.
  • Context: Represents an application program, corresponding to a set of programs usually developed, or a WEB-INF directory and the following web.xml file:
  • Wrapper: Each -Wrapper encapsulates a Servlet.

Tomcat request process

  • The user enters the URL in the browser, and the request is sent to the local port 8080, which is obtained by the Coyote HTTP/1.1 Connector listening there.
  • The Connector passes the request to the Engine (Container) of the Service where it is located, and waits for the Engine's response.
  • Engine gets the request localhost/test/index. jsp, matching all virtual hosts Host.
  • Engine matches the Host named localhost (even if it fails to match, the request will be handed over to the Host, because the Host is defined as the default host of the Engine), and the Host named localhost gets the request /test/index.jsp, which matches All the Context it owns. Host matches the Context whose path is /test (if it fails to match, hand the request to the Context whose path name is "" for processing).
  • The Context of path-" /test" obtains the request /index.jsp, and finds the corresponding Servlet in its mapping table. Context matches the URL
    The pattern is *. jsp Servlet, which corresponds to the JspServlet class.
  • Construct HttpServletRequest object and HttpServletResponse object, call doGet () or doPost() of JspServlet as parameters, execute business logic, data storage, etc.
  • Context returns the HttpServletResponse object after execution to Host.
  • The Host returns the HttpServletResponse object to the Engine.
  • The Engine returns the HttpServletResponse object to the Connector.
  • The Connector returns the HttpServletResponse object to the client Browser.

Tomcat service deployment

Install JDK

Before deploying Tomcat, jdk must be installed, because jdk is a necessary environment for Tomcat to run.

(1) Turn off the firewall, and upload the software packages required to install Tomcat to the /opt directory

systemctl stop firewalld
systemctl disable firewalld
setenforce 0

(2) Install JDK

cd /opt
rpm -qpl jdk-8u201-linux-x64.rpm 
rpm -ivh jdk-8u201-linux-x64.rpm 
java -version

(3) Set JDK environment variables

vim /etc/profile.d/java.sh
export JAVA_HOME=/usr/java/jdk1.8.0_201-amd64
export CLASSPATH=.:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar                        
export PATH=$JAVA_HOME/bin:$PATH

source /etc/profile.d/java.sh
java -version

-------java.sh中补充知识点-----------------------------------
CLASSPATH:编译、运行Java程序时,JRE 会去该变量指定的路径中搜索所需的类( .class)文件。
dt.jar:是关于运行环境的类库,主要是swing 的包。
tools.jar:主要是一 些 jdk 工具的类库,包括 javac, java,javap, javadoc等。
JDK:java development kit ( java开发工具)
JRE:java runtime environment ( java运行时环境)
JVM:java virtuak machine (java虚拟机) ,使 java程序可以在多种平台上运行class文件。

(4) Write a java script to verify the installation

vim kkk.java
#编写一个java程序,输出“hello world!”
public class kkk {
  public static void main(String[] args){
    System.out.println("Hello World!");
  }
}

#检测JDK环境是否设置成功
javac kkk.java
java kkk

Install and start Tomcat

cd /opt/
tar zxvf apache-tomcat-9.0.16.tar.gz
mv apache-tomcat-9.0.16 /usr/local/tomcat

##启动tomcat##
/usr/local/tomcat/bin/startup.sh
netstat -natp | grep  8080

#使用浏览器访问Tomcat的主页 
http://192.168.19.11:8080


Optimize Tomcat startup speed

vim /usr/java/jdk1.8.0_201-amd64/jre/lib/security/java.security
#修改117行;##/dev/random和/dev/urandom都是伪终端,但是/dev/urandom提供的数据流更快
securerandom.source=file:/dev/urandom

#创建一个软连接,将tomcat的命令放入/usr/local/bin
ln -s /usr/local/tomcat/bin/* /usr/local/bin/

#重启Tomcat
shutdown.sh
startup.sh


tomcat's main catalog


Tomcat virtual host configuration

Many times the company will have multiple projects to run, so it is certainly impossible to run multiple Tomcat services on one server, which will consume too much system resources. At this point, you need to use the Tomcat virtual host. For example, two new domain names, www.lei.com and www.dian.com, are now added, and it is hoped that different project contents can be accessed through these two domain names.

(1) Create lei and dian project directories and files

mkdir /usr/local/tomcat/webapps/lei
mkdir /usr/local/tomcat/webapps/dian
echo 'this is lei !' > /usr/local/tomcat/webapps/lei/index.jsp
echo 'this is dian!' > /usr/local/tomcat/webapps/dian/index.jsp

(2) Modify the main Tomcat configuration file

vim /usr/local/tomcat/conf/server.xml
      #165行
      <Host name="www.lei.com"  appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
   <Context docBase="/usr/local/tomcat/webapps/lei" path="" reloadable="true" />
       </Host>
       
       <Host name="www.dian.com"  appBase="webapps" unpackWARs="true"
       autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
   <Context docBase="/usr/local/tomcat/webapps/dian" path="" reloadable="true" />
       </Host>

#重启服务;命令路径优化后可以直接使用shutdown.sh和startup.sh
/usr/local/tomcat/bin/shutdown.sh
/usr/local/tomcat/bin/startup.sh
#----------------参数解释-----------------------------
Host name :主机名
appBase : Tomcat程序工作目录,相对路径为webapps,绝对路径为/usr/local/tomcat/webapps
unpackWARs :是否解压war包
autoDeploy :指示Tomcat运行时,如有新的WEB应用是否允许自动部署
xmlValidation :是否验证xml文件执行有效性检验的标志
xmlNamespaceAware :是否启用xml命名空间,设置该值与xmlValidation为true,表示对web.xml文件执行有效性检验

docBase : WEB应用的目录
path:设置访问的URI为WEB应用的根目录
reloadable :是否在程序有改动时重新载入

(3) Verification

echo "192.168.19.11 www.lei.com www.dian.com" >> /etc/hosts


Tomcat optimization

The default configuration under Tomcat's default installation is not suitable for the production environment. It may frequently appear suspended and needs to be restarted. Only through continuous stress testing and optimization can it run with the highest efficiency and stability. Optimization mainly includes three aspects: operating system optimization (kernel parameter optimization), Tomcat configuration file parameter optimization, and Java virtual machine (JVM) tuning. Today we will take a look at Tomcat configuration file parameter optimization.

Configuration file parameter optimization

Modify the configuration file

vim /usr/local/tomcat/conf/server.xml
     <Connector port="8080" protocol="HTTP/1.1"
                connectionTimeout="20000"
                redirectPort="8443"
                #72行插入
                minSpareThreads="50"
                enableLookups="false"
                disableUploadTimeout="true"
                acceptCount="300"
                maxThreads="500"
                processorCache="500"
                URIEncoding="UTF-8"
                compression="on"
                compressionMinSize="2048"
                compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain,image/gif,image/jpg,image/png" />

#优化就直接用shutdown.sh和startup.sh
/usr/local/tomcat/bin/shutdown.sh
/usr/local/tomcat/bin/startup.sh

At last

Immediately autumn recruits, prepared a large wave of interview questions for everyone! welcome to pay attention to the public account: a bright future, receive a summary of Java interview questions from a major manufacturer + a learning guide for knowledge points + a summary of Java core knowledge points in a 300-page pdf document! These materials are all knowledge points that the interviewer must ask during the interview. The chapter includes a lot of knowledge points, including basic knowledge, Java collections, JVM, multi-threaded concurrency, spring principles, microservices, Netty and RPC, Kafka, diary, design pattern, Java algorithm, database, Zookeeper, distributed cache, data structure, etc.


前程有光
936 声望618 粉丝