<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>数据表格</title>
<%
String pid = request.getParameter("pid");
if(pid == null || pid.trim().length() == 0 )
{
pid = "0";
} %>
<script type="text/javascript" src="js/jquery-easyui-1.4.4/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.4.4/themes/icon.css">
<link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.4.4/themes/default/easyui.css">
<script type="text/javascript" src="js/jquery-easyui-1.4.4/jquery.easyui.min.js"></script>
<script type="text/javascript" src="js/jquery-easyui-1.4.4/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript">
$(function(){
$('#mydg').datagrid({
title:'地区列表',
//singleSelect:true,
width:600,
height:300,
fitColumns:true,
striped:true,
idField:'id',//设置后可实现跨页选择
pagination:true,//分页工具栏
rownumbers:true,
pageSize:5,
pageList:[5,10,15],
sortName:'id',
remoteSort:false,//定义从服务器对数据进行排序。
sortOrder:'desc',
url:'MembersList?pid=<%=pid%>',
toolbar: [{
iconCls: 'icon-add',
text:'增加地区',
handler: function(){
$("#addform").form('reset');
//清理id
$("#id").val(""); $('#add').dialog({
title:'增加地区'
});
$('#add').dialog('open'); }
},'-',{
iconCls: 'icon-edit',
text:'编辑地区',
handler: function(){
var s = $("#mydg").datagrid('getSelected');
if(s == null)
{
alert('请选择一条数据');
}
else
{
alert(s);
//编辑数据
$("#addform").form('reset');
$('#add').dialog({
title:'编辑地区'
});
//绑定数据
$("#addform").form('load',s); $('#add').dialog('open'); }
//alert('编辑按钮')
}
},'-',{
iconCls: 'icon-remove',
text:'删除地区',
handler: function(){
var s = $("#mydg").datagrid('getSelections');
if(s.length > 0)
{
$.messager.confirm('确认','您确认想要删除记录吗?',function(r){
if (r){ var ids = "";
for(var i = 0; i < s.length; i ++)
{
ids += s[i].id;
if(i != s.length - 1)
{
ids += ",";
}
} //alert('ids=' + ids);
$.get("Deletedg?ids=" + ids,
function(data,status)
{
var data = eval('('+ data + ')');
$.messager.show({title:'信息', msg:data.message});
}); $("#mydg").datagrid('reload'); $("#mydg").datagrid('clearSelections');
}
});
}
else
{
alert('请选择数据');
}
}
}], frozenColumns:[[//冻结列
{field:'',checkbox:true},
{field:'id',width:80,title:'ID'}
]],
columns:[[
{field:'parentid',width:80,title:'父ID'},
{field:'name',width:80,title:'地区名',
formatter: function(value,row,index)//列格式化
{
value = '<a href=datagrid.jsp?pid=' + row.id + '>' + value +'</a>' ;
return value; }
},
{field:'postcode',width:80,title:'邮编'}, ]]
});
//按钮
$('#bt').click(function(){
$("#addform").form('submit');
return false;
}); //表单
$("#addform").form({
url:'AddMem',
onSubmit:function(){
//alert('表单测试');
var isValid = $(this).form('validate');
if(!isValid)
{
$.messager.show({title:'信息',msg:'输入有误'});
return false
}
},
novalidate:false,
success:function(data){ var data = eval('('+ data + ')'); $.messager.show({title:'信息', msg:data.message}); if(data.success == true)
{ $("#add").dialog('close');
$("#mydg").datagrid('reload');
} //alert(data.message);
}
});
});
</script>
</head>
<body>
<!--
<table id="mydatagrid" class="easyui-datagrid" style="width:500px;height:300px;"
data-options="url:'',title:'地区列表',singleSelect:true,collapsible:true">
<thead>
<tr>
<th data-options="field:'id',width:100">id</th>
<th data-options="field:'parentid',width:100">父id</th>
<th data-options="field:'name',width:100">地区名</th>
<th data-options="field:'postcode',width:100">邮编</th>
</tr>
</thead>
</table>
-->
<table id="mydg"></table> <div id="add" class="easyui-dialog" style="width:300px" data-options="title:'添加地区',closed:true">
<form id="addform" method="post">
<table>
<tr>
<td>地区名称:</td>
<td><input name="name" class="easyui-textbox"
data-options="required:true,validType:'length[2,5]'"></td>
</tr>
<tr>
<td>邮政编码:</td>
<td><input name="postcode" class="easyui-numberbox"
data-options="required:false,validType:'length[6,6]'"></td> <input type="hidden" value="" name="parentid">
<input type="hidden" value="" name="id" id="id"> </tr>
<tr>
<td colspan="2" align="center"><a href="#" id="bt" style="width:100px" class="easyui-linkbutton">提交</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>

查询Servlet

 package com.hanqi;

 import java.io.IOException;
import java.util.ArrayList; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; /**
* Servlet implementation class jsonMembers
*/
@WebServlet("/jsonMembers")
public class jsonMembers extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public jsonMembers() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//接收地区父id
String pid = request.getParameter("pid"); //如果没有收到,赋初值-1
if(pid == null || pid.trim().length() == 0)
{
pid = "-1";
} try { //实例化集合,接收查询结果
ArrayList<Member> arr = new ArrayList<Member>(); //实例化数据库操作类
AreaDao ad = new AreaDao(); //调用查询方法
arr = ad.selArea(Integer.parseInt(pid)); //初始化向前台输出的json字符串
String str = ""; //如果查询到数据
if(arr != null)
{
//转换成json
str = JSON.toJSON(arr).toString();
} //str = JSON.toJSONString(arr); //输出json
response.getWriter().print(str); }catch (Exception e) { response.getWriter().append(e.getMessage());
} //response.getWriter().append("Served at: ").append(request.getContextPath());
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

增加/修改的Servlet

 package com.hanqi;

 import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class AddMem
*/
@WebServlet("/AddMem")
public class AddMem extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public AddMem() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收表单数据
String name = request.getParameter("name");
String postcode = request.getParameter("postcode");
String parentid = request.getParameter("parentid");
//id用来判断是添加还是修改
String id = request.getParameter("id"); //判断数据是否合法
if(name == null || name.trim().length() == 0)
{
response.getWriter().append("{\"success\":false, \"message\":\"名称不能为空\"}");
}
else if(parentid == null || parentid.trim().length() == 0)
{
response.getWriter().append("{\"success\":false, \"message\":\"父id不能为空\"}");
}
else
{
//转换数据类型
int pid = Integer.parseInt(parentid); //实例化实体类
Member mem = new Member(); //向实体类对象添加参数
mem.setName(name);
mem.setPostcode(postcode);
mem.setParentid(pid); //实例化数据库操作类
AreaDao ad = new AreaDao(); try {
//影响行数
int row = -1; //如果收到id,说明是修改请求
if(id != null && id.trim().length() > 0)
{
int iid = Integer.parseInt(id);
//向实体类对象添加id参数
mem.setId(iid);
//调用修改方法
row = ad.updateArea(mem);
//输出成功信息
response.getWriter().append("{\"success\":true, \"message\":\"成功修改"+row +"条数据\"}");
}
else
{
//没有收到id,则添加数据
row = ad.addArea(mem);
//输出成功信息
response.getWriter().append("{\"success\":true, \"message\":\"成功添加"+row +"条数据\"}");
} } catch (Exception e) {
//异常处理,输出错误信息
response.getWriter().append("{\"success\":false, \"message\":\"错误信息:"+ e.getMessage()+"\"}");
} } //response.setHeader("refresh", "1;URL=memList.jsp?pid=" + parentid);
//response.getWriter().append("Served at: ").append(request.getContextPath());
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

删除的Servlet

 package com.hanqi;

 import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class AddMem
*/
@WebServlet("/AddMem")
public class AddMem extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public AddMem() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收表单数据
String name = request.getParameter("name");
String postcode = request.getParameter("postcode");
String parentid = request.getParameter("parentid");
//id用来判断是添加还是修改
String id = request.getParameter("id"); //判断数据是否合法
if(name == null || name.trim().length() == 0)
{
response.getWriter().append("{\"success\":false, \"message\":\"名称不能为空\"}");
}
else if(parentid == null || parentid.trim().length() == 0)
{
response.getWriter().append("{\"success\":false, \"message\":\"父id不能为空\"}");
}
else
{
//转换数据类型
int pid = Integer.parseInt(parentid); //实例化实体类
Member mem = new Member(); //向实体类对象添加参数
mem.setName(name);
mem.setPostcode(postcode);
mem.setParentid(pid); //实例化数据库操作类
AreaDao ad = new AreaDao(); try {
//影响行数
int row = -1; //如果收到id,说明是修改请求
if(id != null && id.trim().length() > 0)
{
int iid = Integer.parseInt(id);
//向实体类对象添加id参数
mem.setId(iid);
//调用修改方法
row = ad.updateArea(mem);
//输出成功信息
response.getWriter().append("{\"success\":true, \"message\":\"成功修改"+row +"条数据\"}");
}
else
{
//没有收到id,则添加数据
row = ad.addArea(mem);
//输出成功信息
response.getWriter().append("{\"success\":true, \"message\":\"成功添加"+row +"条数据\"}");
} } catch (Exception e) {
//异常处理,输出错误信息
response.getWriter().append("{\"success\":false, \"message\":\"错误信息:"+ e.getMessage()+"\"}");
} } //response.setHeader("refresh", "1;URL=memList.jsp?pid=" + parentid);
//response.getWriter().append("Served at: ").append(request.getContextPath());
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

数据库操作类

 package com.hanqi;

 import java.sql.*;
import java.util.*; //数据操作类
public class AreaDao { //增
public int addArea(Member mem) throws Exception
{
int row = -1;
Connection conn = DBHelper.getConnection();
PreparedStatement ps = null; if(conn != null)
{
try
{
String sql = "insert into MEMBERS(id, parentid, name, postcode) values(sq_members_id.nextval,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, mem.getParentid());
ps.setString(2, mem.getName());
ps.setString(3, mem.getPostcode()); row = ps.executeUpdate();
}
catch(Exception e)
{
throw e;
}
finally
{
ps.close();
} }
conn.close();
return row;
} //修改
public int updateArea(Member mem) throws Exception
{
int row = -1;
Connection conn = DBHelper.getConnection();
PreparedStatement ps = null; if(conn != null)
{
try
{
String sql = "update MEMBERS set parentid=?, name=?, postcode=? where id = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, mem.getParentid());
ps.setString(2, mem.getName());
ps.setString(3, mem.getPostcode());
ps.setInt(4, mem.getId()); row = ps.executeUpdate();
}
catch(Exception e)
{
throw e;
}
finally
{
ps.close();
} }
conn.close();
return row;
} //删除
public int delArea(int id) throws Exception
{
int row = -1;
Connection conn = DBHelper.getConnection();
PreparedStatement ps = null; if(conn != null)
{
try
{
String sql = "delete from MEMBERS where id = ? or parentid = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, id);
ps.setInt(2, id); row = ps.executeUpdate();
}
catch(Exception e)
{
throw e;
}
finally
{
ps.close();
} }
conn.close();
return row;
} //递归方法
private int dg(Connection conn, int id, int row) throws Exception
{ //遍历子节点
PreparedStatement ps = null; PreparedStatement ps1 = null; ResultSet rs =null; try{ String sql = "delete from MEMBERS where id = ?"; ps1 = conn.prepareStatement(sql); ps1.setInt(1, id); row = row + ps1.executeUpdate(); sql = "select * from MEMBERS where parentid = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, id); rs = ps.executeQuery(); if(rs != null)
{ while(rs.next())
{
row = dg(conn, rs.getInt("id"),row);//递归调用
}
} } catch(Exception e)
{
e.printStackTrace(); }
finally
{
try
{
rs.close();
ps.close();
ps1.close(); }
catch(Exception e)
{
throw e;
}
}
return row;
} //递归删除
public int delDG(int id) throws Exception
{
int row = 0; Connection conn = DBHelper.getConnection(); if(conn != null)
{
try
{
//设置手动提交
conn.setAutoCommit(false); //递归级联删除 row = dg(conn,id,row); conn.commit();
}
catch(Exception e)
{
//事务回滚
conn.rollback();
throw e;
} } conn.close();
return row;
} //查询
public ArrayList<Member> selArea(int pid) throws Exception
{
ArrayList<Member> arr = null; Member mem = null; Connection conn = DBHelper.getConnection(); PreparedStatement ps = null; ResultSet rs = null; if(conn != null )
{
try
{ String sql = "select * from MEMBERS where parentid = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, pid); rs = ps.executeQuery(); if(rs != null)
{ arr = new ArrayList<Member>(); while(rs.next())
{ mem = new Member(); mem.setId((rs.getInt("id")));
mem.setParentid(rs.getInt("parentid"));
mem.setName(rs.getString("name"));
mem.setPostcode(rs.getString("postcode")); arr.add(mem);
}
} }
catch(Exception e)
{
throw e;
}
finally
{
try
{
ps.close();
rs.close();
conn.close();
}
catch(Exception e)
{
conn.close();
} }
} return arr;
} //单条查询
public Member getList(int id) throws Exception
{
Member m = null; Connection conn = DBHelper.getConnection(); PreparedStatement ps = null; ResultSet rs = null; if(conn != null )
{
try
{ String sql = "select * from members where id = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, id); rs = ps.executeQuery(); if(rs != null && rs.next())
{
m = new Member(); m.setId(rs.getInt("id"));
m.setParentid(rs.getInt("parentid"));
m.setName(rs.getString("name"));
m.setPostcode(rs.getString("postcode")); } }
catch(Exception e)
{
throw e;
}
finally
{
try
{
ps.close();
rs.close();
conn.close();
}
catch(Exception e)
{
conn.close();
} } } return m;
} //分页查询
public ArrayList<Member> selArea(int pid,int page,int rows) throws Exception
{
ArrayList<Member> arr = null; Member mem = null; Connection conn = DBHelper.getConnection(); PreparedStatement ps = null; ResultSet rs = null; if(conn != null )
{
try
{
int max = page * rows;
int min = (page - 1) * rows; String sql = "select * from (select t.*,rownum rn from (select * from MEMBERS where parentid = ? order by id desc) t where rownum <= ?) where rn > ?"; ps = conn.prepareStatement(sql); ps.setInt(1, pid);
ps.setInt(2, max);
ps.setInt(3, min); rs = ps.executeQuery(); if(rs != null)
{ arr = new ArrayList<Member>(); while(rs.next())
{ mem = new Member(); mem.setId((rs.getInt("id")));
mem.setParentid(rs.getInt("parentid"));
mem.setName(rs.getString("name"));
mem.setPostcode(rs.getString("postcode")); arr.add(mem);
}
} }
catch(Exception e)
{
throw e;
}
finally
{
try
{
ps.close();
rs.close();
conn.close();
}
catch(Exception e)
{
conn.close();
} }
} return arr;
} //记录条数查询
public int getcount(int pid) throws Exception
{
int row = -1; Connection conn = DBHelper.getConnection(); PreparedStatement ps = null; ResultSet rs = null; if(conn != null )
{
try
{ String sql = "select count(1) as rn from MEMBERS where parentid = ?"; ps = conn.prepareStatement(sql);
ps.setInt(1, pid);
rs = ps.executeQuery(); if(rs != null && rs.next())
{
row = rs.getInt("rn");
} }
catch(Exception e)
{
throw e;
}
finally
{
try
{
ps.close();
rs.close();
conn.close();
}
catch(Exception e)
{
conn.close();
} }
} return row;
}
}

实体类

 package com.hanqi;

 //实体类
public class Member { //成员变量设为私有
private int id;
private int parentid;
private String name;
private String postcode; //对外开放getter和setter方法
public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public int getParentid() {
return parentid;
} public void setParentid(int parentid) {
this.parentid = parentid;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPostcode() {
return postcode;
} public void setPostcode(String postcode) {
this.postcode = postcode;
} }

Easyui数据表格-地区列表及工具栏增删改的更多相关文章

  1. easyUI 数据表格datagrid的使用

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  2. 第二百七十七节,MySQL数据库-数据表、以及列的增删改查

    MySQL数据库-数据表.以及列的增删改查 1.创建一个表 CREATE(创建) TABLE(表) ENGINE(引擎) ENGINE=INNODB(引擎)还有很多类引擎,这里只是简单的提一下INNO ...

  3. 商城项目回顾整理(二)easyUi数据表格使用

    后台主页: 商品的数据表格展示 引入用户表数据表格展示 引入日志表数据表格展示 引入订单表数据表格展示 后台主页代码: <%@ page language="java" co ...

  4. jQuery EasyUI - 数据表格(DataGrid)

    由于工作需要,项目使用前端 jQuery EasyUI - DataGrid 来控制数据表格. 1.加载相关js和css,因为easyui依赖jquery,所有加载easyui前要先加载jquery, ...

  5. easyui datagrid 禁止选中行 EF的增删改查(转载) C# 获取用户IP地址(转载) MVC EF 执行SQL语句(转载) 在EF中执行SQL语句(转载) EF中使用SQL语句或存储过程 .net MVC使用Session验证用户登录 PowerDesigner 参照完整性约束(转载)

    easyui datagrid 禁止选中行   没有找到可以直接禁止的属性,但是找到两个间接禁止的方式. 方式一: //onClickRow: function (rowIndex, rowData) ...

  6. abp(net core)+easyui+efcore仓储系统——展现层实现增删改查之控制器(六)

    abp(net core)+easyui+efcore仓储系统目录 abp(net core)+easyui+efcore仓储系统——ABP总体介绍(一) abp(net core)+easyui+e ...

  7. 列表(索引切片 增删改查 嵌套) range 元组的初识

    li = ["alex", "WuSir", "ritian", "barry", "wenzhou" ...

  8. CYQ.Data 数据层框架 CYQ.Data 数据框架 使用篇四 MAction 增删改

    本篇内容概要 本篇继续上一篇内容,本节介绍所有增删改的相关操作. 1:添加数据 Insert方法 2:删除数据 Delete方法 3:更新数据 Update方法 一:添加操作 方法原型: public ...

  9. C# 数据操作系列 - 12 NHibernate的增删改查

    0. 前言 上一篇<C# 数据操作系列 - 11 NHibernate 配置和结构介绍> 介绍了Nhibernate里的配置内容.这一篇将带领大家了解一下如何使用NHIbernate.之前 ...

随机推荐

  1. 敲-PHP与MySQL,JSON

    hi 敲代码~ 1.php与mysql 5.4 修改界面 同样是界面和程序. 界面article.modify.php <?php require_once('../connect.php'); ...

  2. 怎么修改windows命令行字体大小

    打开命令行窗口: 在标题栏处右键单击-->属性,然后更改即可

  3. Unity Camera的两种模式

    http://www.cnblogs.com/zhaoqingqing/p/3302484.html

  4. onSaveInstanceState() 和 onRestoreInstanceState()

    本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceState(),并且在介绍这两个方法之后,再分别来实现使用 ...

  5. RecyclerView,CardView导入和使用(Demo)

    简介: 这篇文章是ANDROID L——Material Design详解(UI控件)的一个补充或者说是应用实例,如果有时间建议大家稍微浏览一下上篇文章. 本文主要介绍Android L新增加的两个U ...

  6. rstudio安装devtool出现“无法解析服务器的名称或地址”问题的解决

    问题:直接使用CRAN的源出现如下错误 Warning in install.packages : InternetOpenUrl failed: '无法解析服务器的名称或地址'Warning in ...

  7. java接口(二)

    1.广义的接口,凡是对外暴露的都可以称作接口. 就像电脑的usb插口. 2.什么时候用接口,什么时候用类? . 3.例子 4.问题:

  8. webpack.optimize.CommonsChunkPlugin插件的使用

    方式一,传入字符串参数 new webpack.optimize.CommonsChunkPlugin('common.js'), // 默认会把所有入口节点的公共代码提取出来,生成一个common. ...

  9. angularjs之$timeout指令

    angular.js的$timeout指令对window.setTimeout做了一个封装,它的返回值是一个promise对象.当定义的时间到了以后,这个promise对象就会被resolve,回调函 ...

  10. Razor 模板自己渲染出结果 string

    using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNet ...