java實現選中刪除功能的例項程式碼
阿新 • • 發佈:2020-02-18
分析:
通過form表單傳遞資料,刪除資料根據id編號刪除。
前臺
<a class="btn btn-primary" href="javascript:void(0);" rel="external nofollow" id="delSelected">刪除選中</a> </div> <form id="form" action="${pageContext.request.contextPath}/delSelectedServlet" method="post"> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox" id="firstCb"></th> <th>編號</th> <th>姓名</th> <th>性別</th> <th>年齡</th> <th>籍貫</th> <th>QQ</th> <th>郵箱</th> <th>操作</th> </tr> <c:forEach items="${users}" var="user" varStatus="s"> <tr> <td><input type="checkbox" name="uid" value="${user.id}"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}" rel="external nofollow" >修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});" rel="external nofollow" >刪除</a></td> </tr> </c:forEach> </table> </form>
Js
<script> function deleteUser(id) { //使用者安全提示 if (confirm("您確定要刪除嗎?")){ //訪問的路徑 location.href=" ${pageContext.request.contextPath}/delUserServlet?id=" rel="external nofollow" +id; } } window.οnlοad=function () { //給刪除選中按鈕新增單擊事件 document.getElementById("delSelected").οnclick=function () { if (confirm("您確定要刪除選中條目嗎?")) //表單提交 document.getElementById("form").submit(); } //1.獲取第一個cb document.getElementById("firstCb").οnclick=function () { //獲取下表所有的cb var cbs=document.getElementsByName("uid"); //遍歷 for (var i=0;i<cbs.length;i++){ //設定這些cbs[i]的checked狀態=firstCb.checked cbs[i].checked =this.checked; } } } </script>
後臺
Servlet
@WebServlet("/delSelectedServlet") public class DelSelectedServlet extends HttpServlet { protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { //獲取所有id String[] ids=request.getParameterValues(“uid”); //呼叫service刪除 UserService service=new UserServiceImpl(); service.delSelectedUser(ids); //跳轉查詢Servlet response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request,IOException { this.doPost(request,response); } }
Service
public void delSelectedUser(String[] ids) { //遍歷陣列 for (String id:ids){ //呼叫dao刪除 dao.deleteUser(Integer.parseInt(id)); } }
Dao
public void updateUser(User user) { String sql=“update userms set name=?,age=?,gender=?,address=?,qq=?,email=? where id=?”; template.update(sql,user.getName(),user.getAge(),user.getGender(),user.getAddress(),user.getQq(),user.getEmail(),user.getId()); }
總結
以上所述是小編給大家介紹的java實現選中刪除功能的例項程式碼,希望對大家有所幫助!