<packaging>war</packaging> <dependencies> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>6.0.0</version> </dependency> <dependency> <groupId>com.csdn</groupId> <artifactId>pro03-fruit-optimize</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
- 第二个pro03-fruit-optimize依赖是本人自己封装的,封装的功能是下面这个博客的项目:https://blog.csdn.net/m0_65152767/article/details/134082847
- 为什么没有加lombok依赖,mysql-connector-java依赖,druid依赖是因为pro03-fruit-optimize这个项目中已经有这些依赖,所以不用再重复添加,jdbc.properties配置文件也在这个依赖里,所以都不用添加
1、index.html
- 一个超链接,跳转到添加库存表单页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>去添加库存</title> </head> <body> <a href="add.html">去添加库存</a> </body> </html>
2、add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>add.html</title> </head> <body> <form action="h03" method="post"> 名称:<input type="text" name="fname"><br> 单价:<input type="text" name="price"><br> 库存:<input type="text" name="fcount"><br> 备注:<input type="text" name="remark"><br> <input type="submit" value="添加"> </form> </body> </html>
3、FruitDao接口
- Fruit 实体类在pro03-fruit-optimize依赖里已经创建
package com.csdn.fruit.dao; import com.csdn.fruit.pojo.Fruit; public interface FruitDao { void addFruit(Fruit fruit); }
4、FruitDaoImpl实现类
package com.csdn.fruit.dao.impl; import com.csdn.fruit.dao.FruitDao; import com.csdn.fruit.pojo.Fruit; import com.csdn.mymvc.dao.BaseDao; public class FruitDaoImpl extends BaseDao<Fruit> implements FruitDao { @Override public void addFruit(Fruit fruit) { super.executeUpdate("insert into t_fruit values(0,?,?,?,?)", fruit.getFname(), fruit.getPrice(), fruit.getFcount(), fruit.getRemark()); } }
5、HTMLServlet类
package com.csdn.servlet; import com.csdn.fruit.dao.FruitDao; import com.csdn.fruit.dao.impl.FruitDaoImpl; import com.csdn.fruit.pojo.Fruit; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/h03") public class HTMLServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //req称之为请求对象 //那么我们可以从请求中获取表单发送过来的数据 //获取请求参数值,参数名是:fname String fname = req.getParameter("fname"); Integer price = Integer.parseInt(req.getParameter("price")); Integer fcount = Integer.parseInt(req.getParameter("fcount")); String remark = req.getParameter("remark"); Fruit fruit = new Fruit(fname, price, fcount, remark); FruitDao fruitDao = new FruitDaoImpl(); fruitDao.addFruit(fruit); //resp表示响应 resp.setCharacterEncoding("UTF-8");//设置响应的编码 resp.setContentType("text/html;charset=utf-8");//告诉浏览器我给你响应的内容类型(MIME-TYPE)是text/html,请你用UTF-8来解释我 PrintWriter out = resp.getWriter(); out.println("<h1>添加成功!</h1>"); out.flush(); } }
6、启动tomcat,填写网页表单,提交数据