基于JQuery easyui,gson的批量新增/修改和删除-servlet版
最近项目需要用到在页面进行批量操作,做了一些这方面的学习,参照网上的资料写了个小例子,记录一下:
- 准备
- 引入gson-2.6.2.jar,这里使用gson而不使用json-lib,原因是json-lib很老了,依赖的jar在后续与struts2整合时,会出现不兼容的警告。而gson很清爽。
- 引入jQuery EasyUI 1.4.4
- 文件结构:
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;
}
}- Bean.java
package com.tjd.study.easyui.servlet; import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tjd.study.easyui.entity.Bean; public class BeanServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public BeanServlet() {
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} @SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
// 获取编辑数据 这里获取到的是json字符串
String deleted = req.getParameter("deleted");
String inserted = req.getParameter("inserted");
String updated = req.getParameter("updated");
System.out.println("--------------------------");
System.out.println("deleted:" + deleted);
System.out.println("inserted:" + inserted);
System.out.println("updated:" + updated + "\n");
Gson gson = new Gson();
Type listType = new TypeToken<List<Bean>>() {
}.getType();
if (deleted != null) {
// 把json字符串转换成对象
System.out.println("deleted:");
list((List<Bean>) gson.fromJson(deleted, listType));
} if (inserted != null) {
// 把json字符串转换成对象
System.out.println("inserted:");
list((List<Bean>) gson.fromJson(inserted, listType));
} if (updated != null) {
// 把json字符串转换成对象
System.out.println("updated:");
list((List<Bean>) gson.fromJson(updated, listType));
}
System.out.println("--------------------------\n");
} private void list(List<Bean> list) {
for (Bean b : list) {
System.out.println(b);
}
} }- BeanServlet
package com.tjd.study.easyui.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson;
import com.tjd.study.easyui.entity.Bean; public class ListBeanServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public ListBeanServlet() {
super();
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Bean> beans = new ArrayList<Bean>();
beans.add(new Bean("Code001", "Code001", 10));
beans.add(new Bean("Code002", "Code002", 20));
beans.add(new Bean("Code003", "Code003", 30));
beans.add(new Bean("Code004", "Code004", 40));
Gson gson = new Gson();
PrintWriter out = response.getWriter();
out.write(gson.toJson(beans));
// 清空缓存
out.flush();
// 关闭
out.close();
} }- ListBeanServlet
/**
*
*/
// 将表单数据转为json
function form2Json(id) {
var arr = $("#" + id).serializeArray();
var jsonStr = ""; jsonStr += '{';
for ( var i = 0; i < arr.length; i++) {
jsonStr += '"' + arr[i].name + '":"' + arr[i].value + '",';
}
jsonStr = jsonStr.substring(0, (jsonStr.length - 1));
jsonStr += '}'; var json = JSON.parse(jsonStr);
return json;
} var dataGrid = (function() {
var editIndex = undefined;
var listActionUrl, commitActionUrl, formId;
var endEditing = function() {
if (editIndex == undefined) {
return true;
}
if ($('#dg').datagrid('validateRow', editIndex)) {
$('#dg').datagrid('endEdit', editIndex);
editIndex = undefined;
return true;
}
return false;
};
return {
setListActionUrl : function(url) {
listActionUrl = url;
},
setCommitActionUrl : function(url) {
commitActionUrl = url;
},
setFormId : function(fid) {
formId = fid;
},
onClickRow : function(index, row) {
if (editIndex != index) {
if (!endEditing()) {
$('#dg').datagrid('cancelEdit', editIndex);
}
}
$('#dg').datagrid('selectRow', index);
editIndex = index;
},
onDblClickRow : function(index) {
if (endEditing()) {
$('#dg').datagrid('selectRow', index).datagrid('beginEdit',
index);
editIndex = index;
} else {
$('#dg').datagrid('selectRow', editIndex);
}
},
append : function() {
if (endEditing()) {
$('#dg').datagrid('appendRow', {});
editIndex = $('#dg').datagrid('getRows').length - 1;
$('#dg').datagrid('selectRow', editIndex).datagrid('beginEdit',
editIndex);
}
},
remove : function() {
if (editIndex == undefined) {
return;
}
$('#dg').datagrid('cancelEdit', editIndex).datagrid('deleteRow',
editIndex);
editIndex = undefined;
},
reject : function() {
$('#dg').datagrid('rejectChanges');
editIndex = undefined;
},
save : function() {
if (endEditing()) {
var $dg = $('#dg');
var rows = $dg.datagrid('getChanges');
if (rows.length) {
var inserted = $dg.datagrid('getChanges', "inserted");
var deleted = $dg.datagrid('getChanges', "deleted");
var updated = $dg.datagrid('getChanges', "updated");
var effectRow = new Object();
if (inserted.length) {
effectRow["inserted"] = JSON.stringify(inserted);
}
if (deleted.length) {
effectRow["deleted"] = JSON.stringify(deleted);
} if (updated.length) {
effectRow["updated"] = JSON.stringify(updated);
} $.post(commitActionUrl, effectRow, function() {
$.messager.alert("提示", "提交成功!");
$dg.datagrid('acceptChanges');
}).error(function() {
$.messager.alert("提示", "提交错误了!");
});
} else {
$.messager.alert("提醒", "未找到任何修改,不能提交!");
return;
}
}
}
};
}());- Default.js
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>easyui</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>BeanServlet</display-name>
<servlet-name>BeanServlet</servlet-name>
<servlet-class>com.tjd.study.easyui.servlet.BeanServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BeanServlet</servlet-name>
<url-pattern>/servlet/commit</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ListBeanServlet</display-name>
<servlet-name>ListBeanServlet</servlet-name>
<servlet-class>com.tjd.study.easyui.servlet.ListBeanServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListBeanServlet</servlet-name>
<url-pattern>/servlet/list</url-pattern>
</servlet-mapping>
</web-app>- web.xml
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery EasyUI datagrid 批量编辑和提交</title>
<link type="text/css" rel="stylesheet" href="resources/themes/default/easyui.css">
<link type="text/css" rel="stylesheet" href="resources/themes/icon.css"> <script type="text/javascript" src="resources/js/jquery.min.js"></script>
<script type="text/javascript" src="resources/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="resources/local/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="resources/js/Default.js"></script>
</head>
<script type="text/javascript">
$(function() {
dataGrid.setCommitActionUrl("servlet/commit");
$("#dg").datagrid({
onClickRow: dataGrid.onClickRow,
onDblClickRow: dataGrid.onDblClickRow
}); $("#add").click(dataGrid.append);
$("#remove").click(dataGrid.remove);
$("#save").click(dataGrid.save); $("#submit_search").click(function () {
$('#dg').datagrid({url : "servlet/list", queryParams: form2Json("searchform") }); //点击搜索
});
});
</script>
<body>
<form name="searchform" method="post" action="" id ="searchform">
<table style="font-size: 12px;">
<tr>
<td height="30">
<a id="submit_search" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls: 'icon-search'">搜索</a>
</td>
</tr>
</table>
</form>
<table id="dg" class="easyui-datagrid" title="批量操作" data-options="url:'',singleSelect:true,fit:true,fitColumns:true,width:700,height:250,toolbar:'#toolBar'">
<thead>
<tr>
<th data-options="field:'code',width:100,editor:'validatebox'">Code</th>
<th data-options="field:'name',width:100,editor:'validatebox'">Name</th>
<th data-options="field:'price',width:100,editor:'numberbox'">Price</th>
</tr>
</thead>
</table>
<div id="toolBar">
<a id="add" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain=true >添加</a>
<a id="remove" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain=true >删除</a>
<a id="save" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-save" plain=true >保存</a>
</div>
</body>
</html>- index.jsp
蜗牛一步两步三步四步往上爬。
基于JQuery easyui,gson的批量新增/修改和删除-servlet版的更多相关文章
- DoNet开源项目-基于jQuery EasyUI的后台管理系统
博主在业余时间开发了一个简单的后台管理系统,其中用到了 jQuery EasyUI 框架,上次分享过系统布局,参考文章:jQuery EasyUI 后台管理系统布局分享,目前已完成系统的整体框架的搭建 ...
- 基于JQuery EasyUI的WebMVC控件封装(含源码)
JQuery EasyUI类库,大家不会陌生,出来已经有很多年了.个人感觉还是很好用的,作者更新频率也很快,bug也及时修复. 最近在整理以前的代码,找到了这个组件,它是将EasyUI组件封装成MVC ...
- jquery easyui使用(四)······添加,编辑,删除
前端: <div style="font-size: 25px; font-weight: 700; margin: 50px 0 10px 10px;"> 车辆登记 ...
- 基于Jquery easyui 选中特定的tab并更新
获取选中的 Tab // 获取选中的 tab panel 和它的 tab 对象 var pp = $('#tt').tabs('getSelected'); var tab = pp.panel('o ...
- jquery tagsinput监听输入、修改、删除事件
个人博客 地址:http://www.wenhaofan.com/article/20181118192458 由于度娘上的根本搜不到对应的操作,连该插件对应的文档介绍都没有,不得已debug了源码才 ...
- 基于jQuery 常用WEB控件收集
Horizontal accordion: jQuery 基于jQuery开发,非常简单的水平方向折叠控件. Horizontal accordion: jQuery jQuery-Horizonta ...
- 一个基于jQuery的简单树形菜单
在工作中的项目使用的是一个前端基于 jQuery easyui 的一个系统,其中左侧的主菜单使用的是 easyui 中的 tree 组件,不是太熟悉,不过感觉不是太好用. 比如 easyui 中的 t ...
- jquery easyUi 配置默认页码
jquery easyUI用pagenation 属性如果修改其默认加载页面显示,配置该怎样写? 注意区分datagrid的pagenation分页的区别,代码如下. if ($.fn.paginat ...
- 基于MVC4+EasyUI的Web开发框架经验总结(12)--利用Jquery处理数据交互的几种方式
在基于MVC4+EasyUI的Web开发框架里面,大量采用了Jquery的方法,对数据进行请求或者提交,方便页面和服务器后端进行数据的交互处理.本文主要介绍利用Jquery处理数据交互的几种方式,包括 ...
随机推荐
- HDU 1111 Secret Code (DFS)
题目链接 题意 : 给你复数X的Xr和Xi,B的Br和Bi,让你求一个数列,使得X = a0 + a1B + a2B2 + ...+ anBn,X=Xr+i*Xi,B=Br+Bi*i : 思路 : 首 ...
- 使用火蜘蛛采集器Firespider采集天猫商品数据并上传到微店
有很多朋友都需要把天猫的商品迁移到微店上去.可在天猫上的商品数据非常复杂,淘宝开放接口禁止向外提供数据,一般的采集器对ajax数据采集的支持又不太好. 还有现在有了火蜘蛛采集器,经过一定的配置,终于把 ...
- 编写高质量代码改善C#程序的157个建议——建议117:使用SSL确保通信中的数据安全
建议117:使用SSL确保通信中的数据安全 SSL(Secure Socket Layer)最初是由NetScape公司设计的,用于Web安全的网络协议.目前它已经广泛应用到各类网络传输通信中了.SS ...
- java中关于Collection和Map相关的类&接口之间的关系
上图(引用自)
- Custom SOLR Search Components - 2 Dev Tricks
I've been building some custom search components for SOLR lately, so wanted to share a couple of thi ...
- python 批量创建文件
# coding:utf8 import os path = "D:/Python_mkfile" os.chdir(path)#切换到该目录 ysyl = u"验收文件 ...
- openedx使用中可能用到的一些资源
这几天一直在弄openedx,你会发现安装好只是第一步,后面还有很多东西在等着你,那么哪里可以看到较新的资料了,分享几个站点: 1.https://readthedocs.org/projects/e ...
- 开源的 .Net Core MVC CMS 推荐
简介 ZKEACMS Core 是基于 ZKEACMS 的 Asp.Net Core 版本. 架设环境: .Net Core 跨平台 Microsoft Sql Serverl 2008 或以上 .N ...
- 基于.net standard 的动态编译实现
在前文[基于.net core 微服务的另类实现]结尾处,提到了如何方便自动的生成微服务的客户端代理,使对于调用方透明,同时将枯燥的东西使用框架集成,以提高使用便捷性.在尝试了基于 Emit 中间语言 ...
- js计算机样式window.getComputedStyle(ele,null)2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...