删除单个商品
DeleteProductByIdServlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String pid = request.getParameter("pid");
ProductService productService = new ProductService();
productService.deleteById(pid);
request.getRequestDispatcher("/ProductFindAllServlet").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
ProductServlet:
/**
* 删除单条数据
* @param pid
* @throws SQLException
*/
public void deleteById(String pid) throws SQLException {
ProductDao productDao = new ProductDao();
productDao.deleteById(pid);
}
ProductDao:
/**
* 删除一条数据
* @param pid
* @throws SQLException
*/
public void deleteById(String pid) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3P0JDBCUtils.getDataSource());
String sql = "delete from product where pid = ?";
queryRunner.update(sql, pid);
}
JS:
function deleteById(pid) {
var flag = window.confirm("壮士,确定要搞我吗?")
if(flag == true) {
window.location.href="${ pageContext.request.contextPath }/DeleteProductByIdServlet?pid="+pid;
}
}
利用复选框删除多条数据
DeleteAllProductServlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] ids = request.getParameterValues("ids");
ProductService productService = new ProductService();
productService.deleteAll(ids);
request.getRequestDispatcher("/ProductFindAllServlet").forward(request, response);
}
ProductService:
/**
* 删除所有数据,采用事务处理方式
* @param ids
*/
public void deleteAll(String[] ids) {
Connection conn = null;
try {
ProductDao productDao = new ProductDao();
conn = C3P0JDBCUtils.getConnection();
conn.setAutoCommit(false);
for (String id : ids) {
productDao.deleteAll(conn,id);
}
DbUtils.commitAndCloseQuietly(conn);
} catch (SQLException e) {
DbUtils.rollbackAndCloseQuietly(conn);
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ProductDao:
/**
* 删除所有数据
* @param conn
* @param id
* @throws SQLException
*/
public void deleteAll(Connection conn, String id) throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "delete from product where pid = ?";
queryRunner.update(conn, sql, id);
}
JS:
$(function(){
$("#selectAll").click(function() {
$("input[id='ids']").prop("checked",this.checked);
});
});
function deleteAllProduct() {
document.getElementById("form1").submit();
}