1.网站学习:廖雪峰网站学习
2.使用js,需要用到js的一个封装包,
复制后粘贴到静态目录js路径下,
3.js语句中包含一个f函数
<script type="text/javascript">
function deleteArticle(id){
if(!confirm("确认要删除选中的记录吗?")) return;
$.ajax({
type: "post",
url: "/ArticleDeleteServlet",
cache : false,
//dataType : "json",
data: "id="+id,
success: function (data) {
console.log(data);
location.href="/ArticleListServlet";
}
});
}
</script>
当我们单击删除时,会出现一个标签,接下来选择是,就会触发下方的ajax语句
ajax是一个新技术,页面不刷新的情况下,就能完成后台的操作
可以去菜鸟教程或者w3c中学习
type: "post",#提交类型为post
url: "/ArticleDeleteServlet",#提交到ArticleDeleteServlet中
cache : false,#不缓存
//dataType : "json",
data: "id="+id,#提交的data是id
success: function (data) { #删除成功后,显示data值,并跳转到ArticleListServlet
console.log(data);
location.href="/ArticleListServlet";
4.完善ArticleDao中的方法,新建deleteArticle方法
public boolean deleteArticle(int id){ String sql = "delete from t_article where id=?"; #定义sql语句 Connection conn = DBUtil.getConnection(); #连接数据库 int count = 0; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); #执行sql语句 ps.setInt(1,id); count = ps.executeUpdate(); #将执行结果放到count中 DBUtil.release(null,null,ps,conn); #释放资源 } catch (SQLException e) { e.printStackTrace(); } if(count==0){ return false; }else { return true; } #判断count,返回不同值 }
5.新建ArticleDeleteServlet
在dopost方法中,调用doget方法
doget方法中
首先得到文章的id()
用Integer.parseInt()方法对id进行数据类型转换
boolean success = dao.deleteArticle(id);
定义一个articleDao类对象dao
使用dao中的deleteArticle方法
boolean success = dao.deleteArticle(id);
对success进行判断
如果成功,向前端反馈一个值
response.getWriter().print("删除成功");
失败了,也向前端反馈一个值
response.getWriter().print("删除失败");
6.id为2的文章被删除