创建Servlet项目
添加引用
打开 https://mvnrepository.com 搜索 servlet 添加框架应⽤到 pom.xml 中,如下图所示:
在项⽬中右键添加“源代码”⽂件夹,如下图所示:
配置路由⽂件 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_3_1.xsd"
version="3.1"
metadata-complete="false">
</web-app>
添加实体类
public class User {
private Integer id;
private String name;
private Integer age;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", password='" + password + '\'' +
'}';
}
}
添加控制器
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;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 17673
* Date: 2022-07-05
* Time: 20:02
*/
@WebServlet("/adduser")
public class AddUser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取参数
String name = req.getParameter("name");
//2.插入数据库
System.out.println("插入数据库");
//3.返回结果
resp.setContentType("test/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().println("添加成功: " + name);
}
}
运行项目(配置tomcat)