[JavaEE Elementary] Tomcat installation and use and first understanding of Servlet

1. Installation and use of Tomcat

1.1 Tomcat installation

Search for Tomcat in the browser and open the official webpage. Tomcat official website
insert image description here
Click to download Tomcat8.
insert image description here
Click to download the compressed package.
insert image description here
After downloading, decompress.
The directory obtained after decompression:
insert image description here
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:
insert image description here
After startup, we can see:
insert image description here
Server startup in xxx msit is a successful startup.

1.3 Tomcat deploys the front-end page

Create a new web page tab, enter 127.0.0.1:8080the Tomcat welcome page. (Tomcat must be running at this time)
insert image description here
8080is 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):
insert image description here
enter in the navigation bar http://127.0.0.1:8080/blog/blog_list.htmlto access through the network.
The first-level path (blog) also has a name, called application path/context path
insert image description here
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
insert image description here
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)
insert image description here
dynamic pages: pages The content changes with different input parameters. (Baidu structure page)
insert image description here

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:

  1. create project
  2. Introduce dependencies
  3. Create directory structure
  4. Write code
  5. packager
  6. Deployment program
  7. verify
  1. Create a project
    Here you need to create a mavenproject.

maven is a "project management" tool. It can:

  1. Standardize directory structure
  2. manage dependencies
  3. Construct
  4. Pack
  5. test
    ...

Open the idea:
insert image description here
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
insert image description here
here:
insert image description here
2. Import dependencies
Open the maven central warehouse and search for Servlet .Choose the version
insert image description here
here 3.1.0.
insert image description here
Copy the maven code to pom.xmlit.
insert image description here
Pay attention to add tags! If there are multiple dependencies, just copy them in.
insert image description here
If the red mark is red for a long time, refresh:
insert image description here
insert image description here
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) mainCreate a webappdirectory under the directory
(2) Create a directory under webapp (3) Create a WEB-INFdirectory under WEB-INF
Next, create a web.xmlfile
insert image description here
(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>

insert image description here
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.

  1. Write code
    insert image description here

(1) HttpServletIt is a ready-made class provided in the Servlet api. Writing Servlet code generally inherits this HttpServlet.
(2) Rewriting doGetmethod

insert image description here
doGetThe method we wrote does not require us to call it manually, but to call it. Tomcat will trigger the method Tomcatwhen 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.getdoGetreqrespreqresp
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.

  1. Package program
    Compile the program, get some .classfiles, 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.
    insert image description here
    Double-click the package to package:
    insert image description here
    by default, maven prints the jar package, and you need to fine-tune the code:
    insert image description here
    repackage:
    insert image description here
  2. Deploy the program Just copy
    the packaged ones to . Start Tomcat.wartomcatwebapps

    insert image description here
  3. Verify
    Enter in the address bar:http://127.0.0.1:8080/hello_servlet/hello
    insert image description here

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.

insert image description here
insert image description here
smart tomcatYou need to configure it for the first time .
insert image description here
Set tomcatthe path
insert image description here
insert image description here
but we can see that the startup failed.
insert image description here
Port 8080 is occupied. You can open cmd and enter the following: you can see
insert image description here
insert image description here

At this point we just need to close Tomcat.
insert image description here
Restart successfully.
insert image description here
insert image description here

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 .
insert image description here
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

  1. 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.
    insert image description here
    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...
  2. 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
    insert image description here
    no Remove the parent class method called by default, such as super.doGet
    insert image description here
  3. 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.
    insert image description here

insert image description here
4. Common mistake 4: A blank page appears.
The logic in the method does not write code like resp.getWriter().write()

  1. 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.

Guess you like

Origin blog.csdn.net/qq_61138087/article/details/131931235