easyui表格的增删改查

时间:2023-03-08 17:46:26
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 、JQuery的js包 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/jquery.min.js"></script>
<!-- css资源 -->
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.4/themes/default/easyui.css">
<!-- 、图标资源 -->
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.4/themes/icon.css">
<!-- 、easyui的js包 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/jquery.easyui.min.js"></script> <!-- 、本地语言 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>
<script type="text/javascript">
//把long型的日期格式转成yyyy-MM-dd格式
function getDate(date)
{
//得到日期对象
var d=new Date(date);
//得到年月日
var year =d.getFullYear();
var month=(d.getMonth()+);
var day= d.getDate();
var rtn=year+"-"+(month<?""+month:month)+"-"+(day<?""+day:day); return rtn;
} var type="add"; $(function(){
//创建data_grid
$("#st").datagrid({ url:'StudentServlet', //数据来源
//冻结列
//列的定义
columns:[[
{field:'idd',checkbox:true},
{field:'sno',title:'学生编号',width:},
{field:'sname',title:'学生姓名',width:},
{field:'ssex',title:'性别',width:,align:'right'},
{field:'sbirthday',title:'生日',width:,align:'center',
formatter: function (value, row, index) {
if(value && value!= "")
{
//var val = new Date(value); //return val.toLocaleDateString(); return getDate(value) }
else
{
return "";
}
} }, {field:'sclass',title:'班级',width:,align:'right'}
]], fitColumns:true,//列自适应宽度,不能和冻结列同时设置为true
striped:true,//斑马线效果
idField:'sno',//主键列
rownumbers:true,//显示行号
singleSelect:false,//是否单选
pagination:true,//显示分页栏
pageList:[,,,],//每页行数选择列表
pageSize:,//出事每页行数
remoteSort:true,//是否服务器端排序,设成false,才能客户端排序
sortName:'sno',//设置排序列
sortOrder:'desc',//排序方式
toolbar:[{iconCls:'icon-search',text:'查询',handler:function(){
//序列化查询表单
var f=$("#form2").serialize();
//alert(f); $("#st").datagrid({url:"StudentServlet?"+f}).datagrid('load'); }},{iconCls:'icon-add',text:'添加',handler:function(){ type="add";
//清楚表单的旧数据
$("#sno").textbox({readonly:false});
$("#form1").form("reset");
$("#saveStu").dialog('open'); }},{iconCls:'icon-edit',text:'修改',handler:function(){ type="edit";
//判断是否选中一条记录
var data=$('#st').datagrid('getSelected');
if(data)
{
//alert(data);
//设置主键字段只读
$("#sno").textbox({readonly:true}); $("#form1").form("reset");
$('#form1').form('load',{sno:data.sno,
sname:data.sname,ssex:data.ssex,sbirthday:getDate(data.sbirthday),
sclass:data.sclass
});
//没有databox可以使用
//$('#form1').form('load',data);
$("#saveStu").dialog({title:'修改学生'}).dialog('open'); }
else
{
$.messager.show({title:'提示',msg:'请选中一条记录'});
} }},{iconCls:'icon-remove',text:'删除',handler:function(){ var data=$('#st').datagrid('getSelections'); if(data.length>)
{
//alert("选中条数="+data.length);
$.messager.confirm("确认","确实要删除吗?",function(r){
if(r)
{
//alert("执行删除sno="+data[0].sno);
//$.get("DeleteStudentServlet?sno="+data[0].sno,
//利用数组,保存选中记录的主键
var snos=[];
for(var i=;i<data.length;i++)
{
snos[i]=data[i].sno;
} $.get("DeleteStudentServlet?snos="+snos,
function(rtn){
var msg=eval("("+rtn+")");
if(msg.success)
{
$('#st').datagrid('reload');
}
$.messager.show({title:"提示",msg:msg.message}); }); }
}); }
else
{
$.messager.show({title:'提示',msg:'请至少选中一条记录'});
} }}]
});
}) </script>
<div id="search" class="easyui-panel" title="查询条件"
data-options="{iconCls:'icon-search',collapsible:true}" style="height:80px;">
<form id="form2" >
<br>
名称:<input class="easyui-textbox" id="sname_s" name="sname_s"> 班级:<input class="easyui-textbox" id="sclass_s" name="sclass_s">
</form> </div>
<table id="st"></table>
<div class="easyui-dialog" id="saveStu" style="width:400px;height:300px;"
title="添加学生" data-options="{closed:true,modal:true,
buttons:[{text:'保存',iconCls:'icon-save',handler:function(){
$('#form1').form('submit',{
url:'SaveStudentServlet?type='+type,
onSubmit:function(){
var isValid = $(this).form('validate'); if (!isValid){
$.messager.show({
title:'消息',
msg:'数据验证未通过'
});
}
return isValid;
},
success:function(data){
var msg=eval('(' +data+ ')');
if(!msg.success)
{
$.messager.show({title:'提示',msg:msg.message});
}
else
{
$('#st').datagrid('reload');
$.messager.show({title:'提示',msg:msg.message});
$('#saveStu').dialog('close');
}
} });
}},
{text:'取消',iconCls:'icon-cancel',handler:function(){$('#saveStu').dialog('close')}}]}"
>
<form action="" id="form1" method="post">
<br><br>
<table border="" width="100%">
<tr>
<td align="right" width="30%">学号:</td>
<td><input class="easyui-textbox" id="sno" name="sno" data-options="{required:true,validType:'length[3,3]'}"></td>
</tr>
<tr>
<td align="right" width="30%">名称:</td>
<td><input class="easyui-textbox" id="sname" name="sname" data-options="{required:true,validType:'length[2,4]'}"></td>
</tr>
<tr>
<td align="right" width="30%">性别:</td>
<td><input type="radio" name="ssex" value="男" checked="checked">男<input type="radio" name="ssex" value="女" >女</td>
</tr>
<tr>
<td align="right" width="30%">生日:</td>
<td><input class="easyui-datebox" id="sbirthday" name="sbirthday"></td>
</tr>
<tr>
<td align="right" width="30%">班级:</td>
<td><input class="easyui-textbox" id="sclass" name="sclass" data-options="{validType:'length[2,5]'}"></td>
</tr>
</table> </form> </div> </body>
</html>

easyui表格的增删改查

package com.hanqi.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hanqi.service.StudentService; /**
* Servlet implementation class StudentServlet
*/
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public StudentServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html"); String spage=request.getParameter("page");
String srows=request.getParameter("rows"); String sort=request.getParameter("sort");
String order=request.getParameter("order"); String sname_s=request.getParameter("sname_s");
if(sname_s!=null)
{
sname_s=new String(sname_s.getBytes("ISO-8859-1"),"UTF-8");
}
String sclass_s=request.getParameter("sclass_s");
if(sclass_s!=null)
{
sclass_s=new String(sclass_s.getBytes("ISO-8859-1"),"UTF-8");
}
if(spage!=null&& srows!=null)
{
int page=Integer.parseInt(spage);
int rows=Integer.parseInt(srows);
Map<String, String> where= new HashMap<String, String>(); where.put("sname_s", sname_s); where.put("sclass_s", sclass_s);
String ls="";
if(sort!=null&&order!=null)
{
ls=sort+" "+order;
}
String json =new StudentService().getPageJSON(page, rows,ls,where); response.getWriter().print(json); }
else
{
response.getWriter().print( "{'title':0,'rows':[]}");
} } /**
* @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.web;

import java.io.IOException;
import java.text.SimpleDateFormat; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.hanqi.entity.Student;
import com.hanqi.service.StudentService; /**
* Servlet implementation class SaveStudentServlet
*/
public class SaveStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public SaveStudentServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
String sno=request.getParameter("sno");
String sname=request.getParameter("sname");
String ssex=request.getParameter("ssex");
String sbirthday=request.getParameter("sbirthday");
String sclass=request.getParameter("sclass");
//接受参数 表示添加或修改 String type=request.getParameter("type"); if(sno!=null && type!=null)
{
String msg="{'success':true,'message':'保存成功'}";
try
{
Student stu=new Student();
stu.setSno(sno);
stu.setSclass(sclass);
stu.setSname(sname);
stu.setSsex(ssex);
if(sbirthday!=null&&!sbirthday.trim().equals(""))
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
stu.setSbirthday(sdf.parse(sbirthday));
}
if(type.equals("add"))
{
new StudentService().addStudent(stu);
}
else
{
new StudentService().editStudent(stu);
}
}
catch(Exception e)
{
msg="{'success':false,'message':'保存不成功,数据异常"+e.getMessage()+"'}";
} response.getWriter().print(msg);
}
else
{
String msg="{'success':false,'message':访问异常}"; response.getWriter().print(msg);
} } /**
* @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.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.hanqi.service.StudentService; /**
* Servlet implementation class DeleteStudentServlet
*/
public class DeleteStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public DeleteStudentServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
String snos=request.getParameter("snos");
System.out.println("1231231312312#####"+snos); if(snos!=null)
{
String msg="{'success':true,'message':'删除成功'}";
try
{
String[] sno=snos.split(",");
for(String s:sno)
{
new StudentService().deleteStudent(s);
} }
catch(Exception e)
{
msg="{'success':false,'message':'删除不成功,数据异常"+e.getMessage()+"'}";
}
response.getWriter().print(msg);
}
else
{ String msg="{'success':false,'message':'访问异常'}"; response.getWriter().print(msg);
} } /**
* @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);
} }

service层

package com.hanqi.service;

import java.util.List;
import java.util.Map; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hanqi.dao.StudentDAO;
import com.hanqi.entity.Student; public class StudentService { //保存
public void addStudent(Student stu)
{
new StudentDAO().insert(stu);
}
//修改
public void editStudent(Student stu)
{
new StudentDAO().update(stu);
}
//删除
public void deleteStudent(String sno)
{
new StudentDAO().delete(sno);
} //查询分页数据
//返回JSON
public String getPageJSON(int page,int rows,String sort,Map<String, String>where)
{
PageJSON<Student> pj=new PageJSON<>(); String rtn=JSONObject.toJSONString(pj);//"{'title':0,'rows':[]}"; int total=new StudentDAO().getTotal(where);
if(total>)
{
List<Student>ls= new StudentDAO().getPageList(page, rows, sort, where); //String ls_json=JSONArray.toJSONString(ls);
//利用转义字符转成JSON格式的语句
//rtn="{\"total\":"+total+",\"rows\":"+ls_json+"}";
pj.setTotal(total);
pj.setRows(ls);
rtn=JSONObject.toJSONString(pj); }
return rtn;
} }

建一个类来封装JSON格式:

package com.hanqi.service;

import java.util.ArrayList;
import java.util.List; public class PageJSON<T> {
//封装Json数据格式
private int total=; private List<T> rows= new ArrayList<T>(); public int getTotal() {
return total;
} public void setTotal(int total) {
this.total = total;
} public List<T> getRows() {
return rows;
} public void setRows(List<T> rows) {
this.rows = rows;
} }
package com.hanqi.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry; import com.hanqi.entity.Student; public class StudentDAO { ServiceRegistry sr=null;
Configuration cfg=null;
SessionFactory sf=null;
Session se=null;
Transaction tr=null; public StudentDAO()
{
cfg=new Configuration().configure(); sr=new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build(); }
//初始化
private void init()
{ sf=cfg.buildSessionFactory(sr);
se=sf.openSession();
tr=se.beginTransaction();
}
//提交和释放资源
private void destory()
{
tr.commit();
se.close();
sf.close();
}
//添加数据的方法
public void insert(Student stu)
{
init();
se.save(stu);
destory();
}
//修改数据的方法
public void update(Student stu)
{
init();
se.update(stu);
destory();
}
//删除数据的方法
public void delete(String sno)
{
init();
//Student stu=(Student)se.get(Student.class, sno);
//se.delete(stu);
//HQL方式执行删除
se.createQuery("delete Student where sno=?").setString(, sno).executeUpdate(); destory();
}
//获取分页的数据集合
public List<Student> getPageList(int page,int rows,String sort,Map<String, String>where )
{
List<Student> rtn=new ArrayList<Student>();
int num=(page-)*rows;
init();
String sql="from Student where 1=1";
String sname=where.get("sname_s");
if(sname!=null&&!sname.equals(""))
{
sql+="and sname=:sname";
}
String sclass=where.get("sclass_s");
if(sclass!=null&&!sclass.equals(""))
{
sql+=" and sclass=:sclass";
}
//排序
if(sort!=null&&!sort.equals(""))
{
sql+=" order by "+sort;
}
Query q=se.createQuery(sql);
if(sname!=null&&!sname.equals(""))
{
q.setString("sname", sname);
}
if(sclass!=null&&!sclass.equals(""))
{
q.setString("sclass", sclass);;
} rtn=q.setFirstResult(num).
setMaxResults(rows).list();
destory();
return rtn;
} //获取数据条数
public int getTotal(Map<String, String>where)
{
int rtn=;
init();
String sql="select count(1) from Student where 1=1";
String sname=where.get("sname_s");
if(sname!=null&&!sname.equals(""))
{
sql+="and sname=:sname";
}
String sclass=where.get("sclass_s");
if(sclass!=null&&!sclass.equals(""))
{
sql+=" and sclass=:sclass";
}
Query q=se.createQuery(sql);
if(sname!=null&&!sname.equals(""))
{
q.setString("sname", sname);
}
if(sclass!=null&&!sclass.equals(""))
{
q.setString("sclass", sclass);;
} List<Object>lo=q.list();
if(lo!=null&&lo.size()>)
{
rtn=Integer.parseInt(lo.get().toString());
} destory();
return rtn;
} }

easyui表格的增删改查

easyui表格的增删改查