码迷,mamicode.com
首页 > Web开发 > 详细

基于JQuery easyui,gson的批量新增/修改和删除-servlet版

时间:2016-06-09 14:39:15      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:

最近项目需要用到在页面进行批量操作,做了一些这方面的学习,参照网上的资料写了个小例子,记录一下:

  1. 准备
    • 引入gson-2.6.2.jar,这里使用gson而不使用json-lib,原因是json-lib很老了,依赖的jar在后续与struts2整合时,会出现不兼容的警告。而gson很清爽。
    • 引入jQuery EasyUI 1.4.4
  2. 文件结构:技术分享技术分享
  3. 技术分享
    package com.tjd.study.easyui.entity;
    
    public class Bean {
        private String code;
        private String name;
        private int price = 0;
    
        public Bean() {
        }
    
        public Bean(String code, String name, int price) {
            this.code = code;
            this.name = name;
            this.price = price;
        }
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getPrice() {
            return price;
        }
    
        public void setPrice(int price) {
            this.price = price;
        }
    
        @Override
        public String toString() {
            return "code=" + code + ",name=" + name + ",price=" + price;
        }
    }
    View Code - Bean.java
    技术分享
     1 package com.tjd.study.easyui.servlet;
     2 
     3 import java.io.IOException;
     4 import java.lang.reflect.Type;
     5 import java.util.List;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 import com.google.gson.Gson;
    13 import com.google.gson.reflect.TypeToken;
    14 import com.tjd.study.easyui.entity.Bean;
    15 
    16 public class BeanServlet extends HttpServlet {
    17     private static final long serialVersionUID = 1L;
    18 
    19     public BeanServlet() {
    20     }
    21 
    22     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    23         doPost(request, response);
    24     }
    25 
    26     @SuppressWarnings("unchecked")
    27     protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
    28         req.setCharacterEncoding("UTF-8");
    29         // 获取编辑数据 这里获取到的是json字符串
    30         String deleted = req.getParameter("deleted");
    31         String inserted = req.getParameter("inserted");
    32         String updated = req.getParameter("updated");
    33         System.out.println("--------------------------");
    34         System.out.println("deleted:" + deleted);
    35         System.out.println("inserted:" + inserted);
    36         System.out.println("updated:" + updated + "\n");
    37         Gson gson = new Gson();
    38         Type listType = new TypeToken<List<Bean>>() {
    39         }.getType();
    40         if (deleted != null) {
    41             // 把json字符串转换成对象
    42             System.out.println("deleted:");
    43             list((List<Bean>) gson.fromJson(deleted, listType));
    44         }
    45 
    46         if (inserted != null) {
    47             // 把json字符串转换成对象
    48             System.out.println("inserted:");
    49             list((List<Bean>) gson.fromJson(inserted, listType));
    50         }
    51 
    52         if (updated != null) {
    53             // 把json字符串转换成对象
    54             System.out.println("updated:");
    55             list((List<Bean>) gson.fromJson(updated, listType));
    56         }
    57         System.out.println("--------------------------\n");
    58     }
    59 
    60     private void list(List<Bean> list) {
    61         for (Bean b : list) {
    62             System.out.println(b);
    63         }
    64     }
    65 
    66 }
    View Code - BeanServlet
    技术分享
     1 package com.tjd.study.easyui.servlet;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import java.util.ArrayList;
     6 import java.util.List;
     7 
     8 import javax.servlet.ServletException;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 import com.google.gson.Gson;
    14 import com.tjd.study.easyui.entity.Bean;
    15 
    16 public class ListBeanServlet extends HttpServlet {
    17     private static final long serialVersionUID = 1L;
    18 
    19     public ListBeanServlet() {
    20         super();
    21     }
    22 
    23     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    24         doPost(request, response);
    25     }
    26 
    27     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    28         List<Bean> beans = new ArrayList<Bean>();
    29         beans.add(new Bean("Code001", "Code001", 10));
    30         beans.add(new Bean("Code002", "Code002", 20));
    31         beans.add(new Bean("Code003", "Code003", 30));
    32         beans.add(new Bean("Code004", "Code004", 40));
    33         Gson gson = new Gson();
    34         PrintWriter out = response.getWriter();
    35         out.write(gson.toJson(beans));
    36         // 清空缓存
    37         out.flush();
    38         // 关闭
    39         out.close();
    40     }
    41 
    42 }
    View Code - ListBeanServlet
    技术分享
      1 /**
      2  * 
      3  */
      4 // 将表单数据转为json
      5 function form2Json(id) {
      6     var arr = $("#" + id).serializeArray();
      7     var jsonStr = "";
      8 
      9     jsonStr += ‘{‘;
     10     for ( var i = 0; i < arr.length; i++) {
     11         jsonStr += ‘"‘ + arr[i].name + ‘":"‘ + arr[i].value + ‘",‘;
     12     }
     13     jsonStr = jsonStr.substring(0, (jsonStr.length - 1));
     14     jsonStr += ‘}‘;
     15 
     16     var json = JSON.parse(jsonStr);
     17     return json;
     18 }
     19 
     20 var dataGrid = (function() {
     21     var editIndex = undefined;
     22     var listActionUrl, commitActionUrl, formId;
     23     var endEditing = function() {
     24         if (editIndex == undefined) {
     25             return true;
     26         }
     27         if ($(‘#dg‘).datagrid(‘validateRow‘, editIndex)) {
     28             $(‘#dg‘).datagrid(‘endEdit‘, editIndex);
     29             editIndex = undefined;
     30             return true;
     31         }
     32         return false;
     33     };
     34     return {
     35         setListActionUrl : function(url) {
     36             listActionUrl = url;
     37         },
     38         setCommitActionUrl : function(url) {
     39             commitActionUrl = url;
     40         },
     41         setFormId : function(fid) {
     42             formId = fid;
     43         },
     44         onClickRow : function(index, row) {
     45             if (editIndex != index) {
     46                 if (!endEditing()) {
     47                     $(‘#dg‘).datagrid(‘cancelEdit‘, editIndex);
     48                 }
     49             }
     50             $(‘#dg‘).datagrid(‘selectRow‘, index);
     51             editIndex = index;
     52         },
     53         onDblClickRow : function(index) {
     54             if (endEditing()) {
     55                 $(‘#dg‘).datagrid(‘selectRow‘, index).datagrid(‘beginEdit‘,
     56                         index);
     57                 editIndex = index;
     58             } else {
     59                 $(‘#dg‘).datagrid(‘selectRow‘, editIndex);
     60             }
     61         },
     62         append : function() {
     63             if (endEditing()) {
     64                 $(‘#dg‘).datagrid(‘appendRow‘, {});
     65                 editIndex = $(‘#dg‘).datagrid(‘getRows‘).length - 1;
     66                 $(‘#dg‘).datagrid(‘selectRow‘, editIndex).datagrid(‘beginEdit‘,
     67                         editIndex);
     68             }
     69         },
     70         remove : function() {
     71             if (editIndex == undefined) {
     72                 return;
     73             }
     74             $(‘#dg‘).datagrid(‘cancelEdit‘, editIndex).datagrid(‘deleteRow‘,
     75                     editIndex);
     76             editIndex = undefined;
     77         },
     78         reject : function() {
     79             $(‘#dg‘).datagrid(‘rejectChanges‘);
     80             editIndex = undefined;
     81         },
     82         save : function() {
     83             if (endEditing()) {
     84                 var $dg = $(‘#dg‘);
     85                 var rows = $dg.datagrid(‘getChanges‘);
     86                 if (rows.length) {
     87                     var inserted = $dg.datagrid(‘getChanges‘, "inserted");
     88                     var deleted = $dg.datagrid(‘getChanges‘, "deleted");
     89                     var updated = $dg.datagrid(‘getChanges‘, "updated");
     90                     var effectRow = new Object();
     91                     if (inserted.length) {
     92                         effectRow["inserted"] = JSON.stringify(inserted);
     93                     }
     94                     if (deleted.length) {
     95                         effectRow["deleted"] = JSON.stringify(deleted);
     96                     }
     97 
     98                     if (updated.length) {
     99                         effectRow["updated"] = JSON.stringify(updated);
    100                     }
    101 
    102                     $.post(commitActionUrl, effectRow, function() {
    103                         $.messager.alert("提示", "提交成功!");
    104                         $dg.datagrid(‘acceptChanges‘);
    105                     }).error(function() {
    106                         $.messager.alert("提示", "提交错误了!");
    107                     });
    108                 } else {
    109                     $.messager.alert("提醒", "未找到任何修改,不能提交!");
    110                     return;
    111                 }
    112             }
    113         }
    114     };
    115 }());
    View Code - Default.js
    技术分享
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     5     id="WebApp_ID" version="2.5">
     6     <display-name>easyui</display-name>
     7     <welcome-file-list>
     8         <welcome-file>index.jsp</welcome-file>
     9     </welcome-file-list>
    10     <servlet>
    11         <description></description>
    12         <display-name>BeanServlet</display-name>
    13         <servlet-name>BeanServlet</servlet-name>
    14         <servlet-class>com.tjd.study.easyui.servlet.BeanServlet</servlet-class>
    15     </servlet>
    16     <servlet-mapping>
    17         <servlet-name>BeanServlet</servlet-name>
    18         <url-pattern>/servlet/commit</url-pattern>
    19     </servlet-mapping>
    20     <servlet>
    21         <description></description>
    22         <display-name>ListBeanServlet</display-name>
    23         <servlet-name>ListBeanServlet</servlet-name>
    24         <servlet-class>com.tjd.study.easyui.servlet.ListBeanServlet</servlet-class>
    25     </servlet>
    26     <servlet-mapping>
    27         <servlet-name>ListBeanServlet</servlet-name>
    28         <url-pattern>/servlet/list</url-pattern>
    29     </servlet-mapping>
    30 </web-app>
    View Code - web.xml
    技术分享
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html>
     4 <html lang="en">
     5 <head>
     6 <meta charset="UTF-8">
     7 <title>JQuery EasyUI datagrid 批量编辑和提交</title>
     8 <link type="text/css" rel="stylesheet" href="resources/themes/default/easyui.css">
     9 <link type="text/css" rel="stylesheet" href="resources/themes/icon.css">
    10 
    11 <script type="text/javascript" src="resources/js/jquery.min.js"></script>
    12 <script type="text/javascript" src="resources/js/jquery.easyui.min.js"></script>
    13 <script type="text/javascript" src="resources/local/easyui-lang-zh_CN.js"></script>
    14 <script type="text/javascript" src="resources/js/Default.js"></script>
    15 </head>
    16 <script type="text/javascript">
    17     $(function() {
    18         dataGrid.setCommitActionUrl("servlet/commit");
    19         $("#dg").datagrid({
    20             onClickRow:    dataGrid.onClickRow,
    21             onDblClickRow: dataGrid.onDblClickRow
    22         });
    23         
    24         $("#add").click(dataGrid.append);
    25         $("#remove").click(dataGrid.remove);
    26         $("#save").click(dataGrid.save);
    27         
    28         $("#submit_search").click(function () {
    29             $(#dg).datagrid({url : "servlet/list", queryParams: form2Json("searchform") });   //点击搜索
    30         });
    31     });
    32 </script>
    33 <body>
    34     <form name="searchform" method="post" action="" id ="searchform">
    35     <table style="font-size: 12px;">
    36         <tr>
    37             <td height="30">
    38                 <a id="submit_search" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls: ‘icon-search‘">搜索</a>
    39             </td>
    40         </tr>
    41     </table>
    42   </form>
    43     <table id="dg" class="easyui-datagrid" title="批量操作" data-options="url:‘‘,singleSelect:true,fit:true,fitColumns:true,width:700,height:250,toolbar:‘#toolBar‘">
    44         <thead>
    45             <tr>
    46                 <th data-options="field:‘code‘,width:100,editor:‘validatebox‘">Code</th>
    47                 <th data-options="field:‘name‘,width:100,editor:‘validatebox‘">Name</th>
    48                 <th data-options="field:‘price‘,width:100,editor:‘numberbox‘">Price</th>
    49             </tr>
    50         </thead>
    51     </table>
    52     <div id="toolBar">
    53         <a id="add" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain=true >添加</a>
    54         <a id="remove" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain=true >删除</a>
    55         <a id="save" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-save" plain=true >保存</a>
    56     </div>
    57 </body>
    58 </html>
    View Code - index.jsp


    蜗牛一步两步三步四步往上爬。

基于JQuery easyui,gson的批量新增/修改和删除-servlet版

标签:

原文地址:http://www.cnblogs.com/icoding-t/p/5572250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!