Table of contents
Prepare Java files
1. First create a new Java project
Select the new project, select Maven as the build system, and click Create
2. Choose to add framework support (in English Add Framework Support
)
3. Choose to add web applications (check Web Application) and JavaEE applications (Java Applications) and click OK
4. web/WEB-INF
Create a new lib folder in the directory
import-servlet-api.jar
- Download tomcat, I downloaded tomcat9.0
Apache Tomcat® - Welcome! - Enter
Project Structure
, click on the library, click on the plus sign + select Java
3. Find the location of the downloaded tomcat file package, open lib, select jsp-api.jar and servlet-api.jar
4. Click OK to open the path under src
5. Right-click to select servlet and create a file
6. New servlet
package org.example; /**
* @author 雫玖
* @version 1.0
* @date 2022/10/1 17:16
*/
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "Servlet", value = "/Servlet")
public class Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
7. Add mapping in web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>org.example.Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
</web-app>
Configure Tomcat server
1. Click Add Configuration in the upper right corner
2. Then click the + sign in the upper left corner and select Tomcat server local
3. Select Deployment
4. Click the plus sign to complete the file deployment, click Apply to complete the deployment
5. Click Run Server
6. Enter the following address in the browser to view
Such a servlet is successfully deployed!