extjs3.4+mysql+servlet的简单增删改查 分页

时间:2021-11-07 11:22:38

模块化简单开发 Startup.js入口js

MainViewPort = Ext.extend(Ext.Viewport, {
layout : 'border',
constructor : function(cfg) {
Ext.apply(this, cfg);
this.initUI();
MainViewPort.superclass.constructor.call(this);
},
initUI : function() {
this.items = [ new Ext.tree.TreePanel({
region : 'west',
width : 260,
loader : new Ext.tree.TreeLoader({
dataUrl : 'servlet/MenuServlet'
}),
rootVisible : false,
root : new Ext.tree.AsyncTreeNode(),
title : 'Menu',
split : true,
listeners : {
click : this.onTreeClicked,
scope : this
}
}), new Ext.TabPanel({
region : 'center'
}), new Ext.Panel({
region : 'north',
height : 100,
border : false,
title : 'Hello'
}) ];
},
onTreeClicked : function(node) {
if (node.leaf) {
var clsString = node.attributes['ref'];
var cls = eval(clsString);
var array = undefined;
array = this.findByType(Ext.TabPanel);
var tabpanel = array && array.length > 0 ? array[0] : undefined;
if (tabpanel) {
var cmp = tabpanel.get(clsString);
if (cmp) {
tabpanel.setActiveTab(cmp);
} else {
var o = new cls({
id : clsString
});
tabpanel.add(o);
tabpanel.setActiveTab(o);
}
}
}
}
});

Ext.onReady(function() {
new MainViewPort();
});

显示数据 UserList .js

UserList = Ext.extend(Ext.Panel,{   title : '用户管理',
layout : 'fit',
constructor : function(cfg) {
Ext.apply(this, cfg);
this.initUI();
UserList.superclass.constructor.call(this);
},
initUI : function() {
this.tbar = [ {
iconCls : 'icon_add',
text : '新增',
scope : this,
handler : function() {
new UserEdit({
userList : this,
userName : 'Add',
}).show();
}
}, {
iconCls : 'icon_edit',
text : '修改',
scope : this,
handler : function() {
var rows = this.gridPanel.getSelectionModel().getSelections();
if (rows.length != 1) {
Ext.MessageBox.alert('提示', '请选择一条记录!');
} else {
new UserEdit({
userList : this,
userName : 'Update',
row : rows
}).show();
}
}
}, {
iconCls : 'icon_delete',
text : '删除',
handler : this.onDelete,
scope : this
}, '->', {
iconCls : 'icon_query',
text : '查询'
}, {
iconCls : 'icon_refresh',
text : '刷新',
scope : this,
handler : function() {
this.refresh();
}
} ];

this.store = new Ext.data.JsonStore({
url : 'servlet/UserServlet',
totalProperty : 'totalCount',
root : 'rows',
fields : [ 'id', 'name', 'age', 'gender' ]
});

this.sm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true
});

this.bbar = new Ext.PagingToolbar({
pageSize : 10,
store : this.store,
beforePageText : "当前第",
afterPageText : "页,共{0}页",
displayInfo : true,
displayMsg : "当前显示 {0} - {1}条,共 {2}",
emptyMsg : "没有记录"
});

this.gridPanel = new Ext.grid.GridPanel({
store : this.store,
border : false,
viewConfig : {
forceFit : true
},
loadMask : {
msg : '正在加载中...'
},
sm : this.sm,
columns : [ this.sm, new Ext.grid.RowNumberer(), {
header : 'ID',
dataIndex : 'id',
sortable : true,
hidden : true
}, {
header : '姓名',
dataIndex : 'name',
sortable : true
}, {
header : '年龄',
dataIndex : 'age',
sortable : true
}, {
header : '性别',
dataIndex : 'gender',
sortable : true,
renderer : this.onRendererOfGender
} ]
});

this.store.load({
params : {
start : 0,
limit : 10
}
});

this.items = this.gridPanel;

},
onRendererOfGender : function(v) {
if (v == 1) {
return '男';
} else if (v == 0) {
return '女';
} else {
return '';
}
},
onDelete : function() {
var rows = this.gridPanel.getSelectionModel().getSelections();
if (rows.length > 0) {
Ext.MessageBox.confirm('提示', '您确实要删除选定的记录吗?', function(btn) {
if (btn == 'yes') {
var rows = this.gridPanel.getSelectionModel()
.getSelections();// 选中的行
var selectedKeys;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
selectedKeys = row.get("id");
}
Ext.MessageBox.show({
msg : '正在请求数据, 请稍侯',
progressText : '正在请求数据',
width : 300,
wait : true,
waitConfig : {
interval : 200
}
});
Ext.Ajax.request({
url : 'servlet/DeleteUserServlet',
method : 'POST',
params : {
USER_ID : selectedKeys
},
failure : function() {
Ext.MessageBox.hide();
Ext.MessageBox.alert("警告", "出现异常错误!");
},
success : function() {
Ext.MessageBox.hide();
Ext.MessageBox.alert("成功", "删除成功!");
this.gridPanel.store.reload();
},
scope : this
});
}
}, this);
} else {
Ext.MessageBox.alert('提示', '请至少选择一条记录!');
}
},
refresh : function() {
this.gridPanel.store.reload();
}
});

增删改窗口 UserEdit .js

UserEdit = Ext.extend(Ext.Window, {
layout : 'fit',
width : 400,
height : 200,
modal : true,
closeAction : 'hide',
plain : true,
record : undefined,
title : '添加用户',
constructor : function(cfg) {
Ext.apply(this, cfg);
this.initUI();
UserEdit.superclass.constructor.call(this);
},
initUI : function() {
if (this.userName == 'Add') {
this.buttons = [ {
text : '保存',
handler : this.onAdd,
scope : this
}, {
text : '取消',
scope : this,
handler : function() {
this.userForm.form.reset();
this.hide();
}
} ];
} else if (this.userName == 'Update') {
this.title = "修改用户";
this.buttons = [ {
text : '修改',
handler : this.onUpdate,
scope : this
}, {
text : '取消',
scope : this,
handler : function() {
this.userForm.form.reset();
this.hide();
}
} ];
}

this.userForm = new Ext.FormPanel({
labelWidth : 75,
frame : true,
bodyStyle : 'padding:5px 5px 0',
waitMsgTarget : true,
defaults : {
width : 230
},
defaultType : 'textfield',
listeners : {
scope : this,
render : function(cmp) {
if (this.userName == 'Update') {
cmp.getForm().loadRecord(this.row[0]);
}
}
},
items : [ {
fieldLabel : 'id',
name : 'id',
emptyText : '5',
hidden : true,
hideLabel : true,
allowBlank : true
}, {
fieldLabel : '姓名',
name : 'name',
emptyText : '姓名',
allowBlank : false
}, {
fieldLabel : '年龄',
name : 'age',
emptyText : '年龄',
xtype : 'numberfield',
allowBlank : false
}, new Ext.form.RadioGroup({
fieldLabel : '性别',
name : 'gender',
items : [ {
boxLabel : '男',
name : 'gender',
inputValue : 1
}, {
boxLabel : '女',
name : 'gender',
inputValue : 0
} ]
}), ]
});

this.items = this.userForm;

},
onAdd : function() {
if (this.userForm.form.isValid()) {
this.userForm.form.submit({
url : 'servlet/AddUserServlet',
waitMsg : '正在保存数据,稍后...',
success : function(form, action) {
Ext.Msg.alert('保存成功', '添加用户信息成功!');
this.userForm.form.reset();// 清空表单
this.userList.refresh();
this.hide();
},
failure : function(form, action) {
Ext.Msg.alert('保存失败', '添加用户信息失败!');
},
scope : this
});
} else {
Ext.Msg.alert('信息', '请填写完成再提交!');
}
},
onUpdate : function() {
if (this.userForm.form.isValid()) {
this.userForm.form.submit({
clientValidation : true,// 进行客户端验证
waitMsg : '正在提交数据请稍后...',// 提示信息
waitTitle : '提示',// 标题
url : 'servlet/UpdateUserServlet',// 请求的url地址
method : 'POST',// 请求方式
success : function(form, action) {// 加载成功的处理函数
this.hide();
this.userForm.form.reset();// 清空表单
this.userList.refresh();
Ext.Msg.alert('提示', '修改信息成功');
},
failure : function(form, action) {// 加载失败的处理函数
Ext.Msg.alert('提示', '修改信息失败');
},
scope : this
});
} else {
Ext.Msg.alert('信息', '请填写完成再提交!');
}
}
});

jsp页面代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>ExtJs Sample</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<script type="text/javascript" src="resource/ext-3.4.0/adapter/jquery/ext-jquery-adapter.js"></script>
-->

<link rel="stylesheet" type="text/css" href="resource/ext-3.4.0/resources/css/ext-all.css"/>
<link rel="stylesheet" type="text/css" href="resource/css/icon.css"/>
<script type="text/javascript" src="resource/ext-3.4.0/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="resource/ext-3.4.0/ext-all.js"></script>
<script type="text/javascript" src="module/Startup.js"></script>

<script type="text/javascript" src="module/UserList.js"></script>
<script type="text/javascript" src="module/UserEdit.js"></script>

</head>
<body>
</body>
</html>

后台查询分页代码

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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.issrv.extjssample.dao.UserDao;
import com.issrv.extjssample.entity.User;

import net.sf.json.JSONObject;

public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int start = 0;
int pageSize = 10;
if (!request.getParameter("start").equals("")) {
start = Integer.parseInt(request.getParameter("start"));
}

if (!request.getParameter("limit").equals("")) {
pageSize = Integer.parseInt(request.getParameter("limit"));
}

List list = new ArrayList();

List<User> list1 = UserDao.queryUserForPage(start, pageSize);// 分页数据
// 数据库分页

for (User u : list1) {
list.add(u);
}

Map jsonMap = new HashMap();
jsonMap.put("rows", list);
jsonMap.put("success", true);
jsonMap.put("totalCount", UserDao.queryUserLen());// 总行数
System.out.println(JSONObject.fromObject(jsonMap).toString());
out.println(JSONObject.fromObject(jsonMap).toString());
out.flush();
out.close();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}