持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第26天,点击查看活动详情
添加和删除
删除
现在图片上添加一个delete事件
<td><img src="imgs/1.jpg" class="image" th:onclick="|delFruit(${fruit.fid})|"></td>
编写delFruit事件
function delFruit(fid){
if (confirm("是否确认删除?")){
window.location.href='del.do?fid='+fid
}
}
当点击确认按钮后,会跳转到del.do?fid=fid,所以需要写一个/del.do来接受参数
@WebServlet("/del.do")
public class DelServlet extends ViewBaseServlet {
private FruitDao fruitDao=new FruitDaoImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fidStr = req.getParameter("fid");
if (fidStr!=null && !"".equals(fidStr)){
int fid = Integer.parseInt(fidStr);
fruitDao.delteFruit(fid);
resp.sendRedirect("index");
}
}
}
当删除后重定向到index界面
添加
在index.html写一个添加库存的链接
<div id="add_fruit">
<a href="add.html">添加库存记录</a>
</div>
跳转到add.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/test.css">
<script language="JavaScript" src="js/index.js"></script>
</head>
<body>
<div id="div">
<div id="div_list">
<form action="add.do" method="post">
<table id="tbl_list">
<p class="p">添加水果库存!</p>
<tr>
<th>名称:</th>
<!--<td><input type="text" name="fname" th:value="${fruit.fname}"></td>-->
<td><input type="text" name="fname"></td>
</tr>
<tr>
<th>单价:</th>
<td><input type="text" name="price" ></td>
</tr>
<tr>
<th>库存:</th>
<td><input type="text" name="fcount"></td>
</tr>
<tr>
<th>备注:</th>
<td><input type="text" name="remark" ></td>
</tr>
<tr>
<th colspan="2">
<input type="submit" value="添加">
</th>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
当点击添加时,会将传入的数据传到/add.do,最终实现添加效果
@WebServlet("/add.do")
public class AddServlet extends ViewBaseServlet {
private FruitDao fruitDao=new FruitDaoImpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、设置编码
req.setCharacterEncoding("UTF-8");
//2、获取参数
String fname = req.getParameter("fname");
String priceStr = req.getParameter("price");
int price = Integer.parseInt(priceStr);
String fcountStr = req.getParameter("fcount");
int fcount = Integer.parseInt(fcountStr);
String remark = req.getParameter("remark");
//3、执行更新
fruitDao.insertFruit(new Fruit(0,fname,price,fcount,remark));
//4、资源跳转
//super.processTemplate("index",req,resp);
resp.sendRedirect("index");
}
}
这里是通过index.html直接跳转到了add.html,所以在add.html就无法使用thymeleaf了,因为thymeleaf是在Servlet中渲染的,而通过index.html—> add.html之间的跳转并没有经过Serlvet,所以如果协程
th:action="@{/add.do",则不会被解释如果想解决此问题,也可以在index.html中先跳转到add.do此时就经过了thymeleaf的渲染,之后再添加一个doGet方法,因为当访问add.do时,其实就相当于调用了doGet,内容为super.processTemplate("add",req,resp);跳转到add.html,此时点击添加之后再跳转到doPost方法就不会再出现任何问题