Article Directory
1. Installation and use of Tomcat
1.1 Tomcat installation
Search for Tomcat in the browser and open the official webpage. Tomcat official website
Click to download Tomcat8.
Click to download the compressed package.
After downloading, decompress.
The directory obtained after decompression:
The following is a partial explanation of the above key files:
bin
: Executable program/script. Start Tomcat here.conf
: Configuration, using xml format to represent the configuration of the server, such as modifying the port number bound to tomcat, you need to modify the content here.lib
: Some libraries that tomcat depends on. (Not considered for the time being)logs(重要)
: Log, the log of tomcat operation is here. If there is a problem with the program, how to troubleshoot? Just look at this log.webapps
: Each webapp is a "website". Multiple websites can be deployed on one tomcat, which is called "webapps" here. There are many directories here, and each directory is regarded as an independent website. The code we learn later It is also deployed in this webapps.
1.2 Startup of Tomcat
Tomcat startup:
After startup, we can see:
Server startup in xxx ms
it is a successful startup.
1.3 Tomcat deploys the front-end page
Create a new web page tab, enter 127.0.0.1:8080
the Tomcat welcome page. (Tomcat must be running at this time)
8080
is the default port number of Tomcat. Just like the default port number of MySQL 3306
. Next, we
try to deploy the front-end code in Tomcat: Take
the blog system code learned earlier as an example:
copy the blog system to the webapps folder (deployment):
enter in the navigation bar http://127.0.0.1:8080/blog/blog_list.html
to access through the network.
The first-level path (blog) also has a name, called application path/context path
this The page is different from the previous one. This is accessed through the network. The previous page is accessed through the file path. The network
access can be accessed across hosts, and the path can only access pages on its own host.
2. Servlet
2.1 What is Servlet
Servlet
: It is a technology to realize dynamic pages . It is a native web development API provided by Tomcat to java.
Web pages are divided into two categories:
static pages: the content of the pages is always fixed. (Baidu homepage)
dynamic pages: pages The content changes with different input parameters. (Baidu structure page)
2.2 The first Servlet program
Let's write a hello world program first: it is expected to write a Servlet program and deploy it to Tomcat, access it through a browser, and get the hello world string.
There are seven steps in total:
- create project
- Introduce dependencies
- Create directory structure
- Write code
- packager
- Deployment program
- verify
- Create a project
Here you need to create amaven
project.
maven is a "project management" tool. It can:
- Standardize directory structure
- manage dependencies
- Construct
- Pack
- test
...
Open the idea:
Note: When you use maven for the first time, after the project is created, you will read the article below and load some maven dependencies from the central warehouse. It takes a long time. Pay attention to the directory
here:
2. Import dependencies
Open the maven central warehouse and search for Servlet .Choose the version
here 3.1.0
.
Copy the maven code to pom.xml
it.
Pay attention to add tags! If there are multiple dependencies, just copy them in.
If the red mark is red for a long time, refresh:
3. Create a directory structure
Although maven has automatically created it for us Some directories, but not enough. Here you need to use maven to develop a web program, and you need other directories.
(1) main
Create a webapp
directory under the directory
(2) Create a directory under webapp (3) Create a WEB-INF
directory under WEB-INF
Next, create a web.xml
file
(4) and write the following code in web.xml.
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
The Servlet program we wrote is equivalent to the carriage. Tomcat is equivalent to the front of the car. We put the written Servlet program in the webapps directory, which is equivalent to hanging the carriage on the front of the car. How does Tomcat identify which ones in the webapps directory need to be pulled and run? The compartments, which are not. It needs to be identified by the code we copy and paste. (WEN-INF/web.xml). It
is equivalent to the name certificate.
- Write code
(1) HttpServlet
It is a ready-made class provided in the Servlet api. Writing Servlet code generally inherits this HttpServlet.
(2) Rewriting doGet
method
doGet
The method we wrote does not require us to call it manually, but to call it. Tomcat will trigger the method Tomcat
when it receives the request . Tomcat will construct two parameters, and . Among them are the strings read from the TCP socket, according to The object parsed by the HTTP protocol. It is an empty object (the programmer constructs resp according to the request req and business logic in doGet) resp is an output parameter. : Calculate the response according to the request. This method of the parent class just returns an error page , need to be deleted.get
doGet
req
resp
req
resp
doGet
super.doGet();
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//注解是java中特殊的类,Java专门定义了一种"语法糖"来实现注解
//注解的作用,针对一个类/方法,进行额外的"解释说明"
//赋予了这个类.方法额外的功能/含义
//Tomcat实现的
//此处 @WebServlet("/hello") 的作用是:
//把当前的类,和一个HTTP请求的路径关联起来
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//在服务器的控制台里打印
System.out.println("hello world");
//将helloworld返回到客户端.
//getWriter()会创建一个 write 对象
//此处的 write 操作其实是往resp的body部分进行写入.
//等resp对象整个构造好了,tomcat会统一转成 HTTP 相应的格式再写 socket
resp.getWriter().write("hello world");
}
}
doGet is called by Tomcat when it receives a Get request. Whether it is low or not, it depends on the path of the current GET request. Different paths can trigger different codes . (Associated with different classes)
In the Servlet program, there can be many Servlet classes, and each Servlet class can be associated with different paths (corresponding to different resources). Therefore, multiple Servlets here implement different functions.
- Package program
Compile the program, get some.class
files, and then pack these .classes into a compressed package.
A jar package is a compressed package composed of .classes, but here we need to package a war package. A jar package is just an ordinary java program. The package is tomcat's exclusive program to describe the webapp. A war package is a webapp.
Double-click the package to package:
by default, maven prints the jar package, and you need to fine-tune the code:
repackage:
- Deploy the program Just copy
the packaged ones to . Start Tomcat.war
tomcat
webapps
- Verify
Enter in the address bar:http://127.0.0.1:8080/hello_servlet/hello
Summary: After entering the url in the browser, the browser constructs a corresponding HTTP GET request and sends it to tomcat. Tomcat determines the specific webapp according to the first-level path, and determines which one to call according to the second-level path. Class. Then determine which method (doGET, doPost) to call HelloServlet through the GET/POSE method
In the above process, the two processes of 5 packaging and 6 deployment programs can use the Tomcat plug-in of IDEA to integrate Tomcat into IDEA. This saves us the process of manual packaging. The process of manual deployment only needs to be clicked to run. Automatic packaging and deployment.
Automatic package deployment based on tomcat plug-in , suitable for development stage, frequently modify code verification. Manual package deployment , suitable for online stage, release program.
Use the tomcat plug-in:
plug-in: function extension . IDEA provides some APIs that allow programmers to develop plug-ins and extend the existing functions of IDEA.
smart tomcat
You need to configure it for the first time .
Set tomcat
the path
but we can see that the startup failed.
Port 8080 is occupied. You can open cmd and enter the following: you can see
At this point we just need to close Tomcat.
Restart successfully.
The working principle of smart tomcat:
instead of automatically copying the war package (unchanged in webapps), it is to start tomcat in another way. Tomcat supports specifying a specific webapp directory when starting, which is equivalent to letting tomcat load a single webapp to run .
IDEA directly calls tomcat to let tomcat load the directory in the current project.
http://127.0.0.1:8080/ is followed by the context path.
If it is deployed by directly copying the war package, the context path is the name of the war package (directory name).
If it is deployed by smart tomcat, it can be configured here The default is the project name.
These two deployments are actually two ways of running tomcat, and they have different understandings of context path, so special attention should be paid when using them.
2.3 Common errors
- Common error 1: 404
404 means that the resource accessed by the user does not exist, the high probability is that the URL path is written incorrectly.
Or your webapp is not deployed correctly: web.xml is wrongly written, the file name is wrong, and the file path is wrong ok, the file location is wrong... - Common error 2: 405
405 means that the corresponding HTTP request method has not been implemented. For example, if we send a GET request in the browser, but doGet is not written in the code, 405 will appear at this time. It may also be that there is
no Remove the parent class method called by default, such as super.doGet
- Common error 3: 500
is often caused by an exception thrown in the Servlet code. This problem is best solved, because when 500 occurs, the page log will clearly tell you the exception call stack and which line of code caused the exception. For example, we give the
code A null pointer exception occurs.
4. Common mistake 4: A blank page appears.
The logic in the method does not write code like resp.getWriter().write()
- Common error 5: The page cannot be accessed.
The most common reason is that Tomcat has not started or crashed. If we shut down Tomcat, the page cannot be accessed. If Tomcat cannot start, it may be a port conflict.