在struts中使用checkbox實現批量刪除- -

JSP
 <form id = "delForm" method = "post">
      <logic:iterate id="bean" name="beanList" >
         <tr>
            <td><input type = "checkbox" name = "ids" value = '<bean:write name = "bean" property = "id"/>'></td>
            <td>.....</td>
         </tr>
      </logic:iterate>
    <input type = "button" value = "全選" onclick = "for (var i = 0; i < delForm.questionIds.length; i ++){delForm.questionIds[i].checked = true;}"/>
    <input type = "button" value = "反選" onclick = "for (var i = 0; i < delForm.questionIds.length; i ++){delForm.questionIds[i].checked = false;}"/>
    <input type = "button" value = "刪除選中" onclick = "if(confirm('真的要刪除選中內容?'))delForm.submit()"/>
 </form>

FormBean( 我使用的是DynaActionForm,所以在struts-config.xml中配置)
  <form-bean name="testingForm"  type="org.apache.struts.action.DynaActionForm">
    <form-property name="id"     type="java.lang.String"/>
    <form-property name="ids"    type="java.lang.String[]"/>
     ........
  </form-bean>
 
Action
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        // 獲取操作名
        DynaActionForm dyna = (DynaActionForm) form;
        // ids數組是所有被選中記錄的id值
        String[] ids = (String[]) dyna.get("ids");
       // 調用相應dao方法,完成刪除所有指定id操作
       return mapping.findForward(".....");
    }
 
說明
       關鍵就在於FormBean的設置,也就是那個數組ids,一般的實現方法會在客戶端首先遍歷一遍所有被選中的checkbox,然後使用js拼裝字符串,傳給action,在後臺解析該字符串得到所有被選中的指定的id,這個方法沒有什麼不妥,不過使用struts會更簡單些,而這裏使用一個FormBean的數組屬性來對應頁面中的 checkbox DHTML數組對象,struts替我們完成了遍歷所有checkbox,並找出所有被選中checkbox的value,是不是更簡單呢?還有一個需要搞明白的就是html:iterate所用的Bean和執行批量刪除操作的FormBean是兩碼事,我開始就差點搞混淆了。
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章