前端代码:

Ext.onReady(function(){
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: [{name: 'id',
type: 'int',
useNull: true
}, 'email', 'first', 'last'],
validations: [{ type: 'length',
field: 'email',
min: 1
}, {type: 'length',
field: 'first',
min: 1
}, {type: 'length',
field: 'last',
min: 1
}]
});
//构造store
var store = Ext.create('Ext.data.Store', {
//autoLoad: true,
autoSync: true,
model: 'Person',
proxy: {
type: 'ajax',
api: {
read: '<%=basePath %>/AdminServlet?param=read',//查询
create: '<%=basePath %>/AdminServlet?param=add',//创建
update: '<%=basePath %>/AdminServlet?param=update',//更新
destroy: '<%=basePath %>/AdminServlet?param=deletes'//删除
},
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json'
}
},
listeners: {
write: function(store, operation){
var record = operation.getRecords()[0],
name = Ext.String.capitalize(operation.action),
verb; if (name == 'Destroy') {
record = operation.records[0];
verb = 'Destroyed';
} else {
verb = name + 'd';
}
Ext.example.msg(name, Ext.String.format("{0} user: {1}", verb, record.getId()));
}
}
}); store.load({
params:{
start:0,
limit:20
}
});
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
id:'edit',
listeners: {
edit:function(rowEditing,context){
context.record.commit();
store.reload();//提交后重新加载 获取新数据 包括自动生成的id
},
cancelEdit: function(rowEditing, context) {
// Canceling editing of a locally added, unsaved record: remove it
if (context.record.phantom) {
store.remove(context.record);
}
}
}
}); //创建 panel
var grid = Ext.create('Ext.grid.Panel', {
renderTo: document.body,
plugins: [rowEditing],
width: 400,
height: 300,
frame: true,
title: 'Users',
store: store,
iconCls: 'icon-user',
columns: [{
text: 'ID',
width: 40,
sortable: true,
dataIndex: 'id'
}, {
text: 'Email',
flex: 1,
sortable: true,
dataIndex: 'email',
field: {
xtype: 'textfield'
}
}, {
header: 'First',
width: 80,
sortable: true,
dataIndex: 'first',
field: {
xtype: 'textfield'
}
}, {
text: 'Last',
width: 80,
sortable: true,
dataIndex: 'last',
field: {
xtype: 'textfield'
}
}],
dockedItems: [{
xtype: 'toolbar',
items: [{
text: 'Add',
iconCls: 'icon-add',
handler: function(){
// empty record
store.insert(0, new Person());//从指定索引处开始插入 插入Model实例 并触发add事件
rowEditing.startEdit(0, 0);//开始编辑,并显示编辑器 }
}, '-', {
itemId: 'delete',
text: 'Delete',
iconCls: 'icon-delete',
disabled: true,
handler: function(){
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (selection) {
store.remove(selection);
}
}
}]
}]
});
grid.getSelectionModel().on('selectionchange', function(selModel, selections){
grid.down('#delete').setDisabled(selections.length === 0);
}); });

后台代码:

/**
* @author Lucare(fcs)
*
* 2015年1月9日
*/
public class AdminServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private Connection con;
private List<Admin> admins;
private int count; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {
//根据参数param分发请求
String param = request.getParameter("param");
System.out.println(param);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ext","root","root");
Gson gson = new Gson();
response.setCharacterEncoding("UTF-8");
if(param.equals("read")){
String start = request.getParameter("start");
String limit = request.getParameter("limit");
admins = findAll(start, limit);
count = totalCount();
response.getWriter().print("{total:"+count+",data:"+gson.toJson(admins)+"}");
}else if(param.equals("add")){
//extjs 以流的形式传递数据(json类型)
String msg = request.getReader().readLine();
Admin admin = gson.fromJson(msg, Admin.class);
add(admin);
}else if(param.equals("update")){
String msg = request.getReader().readLine();
Admin admin = gson.fromJson(msg, Admin.class);
update(admin);
}else if(param.equals("deletes")){
String msg = request.getReader().readLine();
Admin admin = gson.fromJson(msg, Admin.class);
del(admin);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
closeCon();
}
} public List<Admin> findAll(String start,String limit){
List<Admin> adminlist = new ArrayList<Admin>();
try {
PreparedStatement ps = con.prepareStatement("select * from admins limit "+start+","+limit);
ResultSet rs = ps.executeQuery();
while(rs.next()){
Admin admin = new Admin();
admin.setId(rs.getInt(1));
admin.setEmail(rs.getString(2));;
admin.setFirst(rs.getString(3));
admin.setLast(rs.getString(4));
adminlist.add(admin);
}
} catch (SQLException e) {
e.printStackTrace();
}
return adminlist;
} public void add(Admin admin){
try {
PreparedStatement ps = con.prepareStatement("insert into admins values(null,?,?,?)");
ps.setString(1, admin.getEmail());
ps.setString(2, admin.getFirst());
ps.setString(3, admin.getLast());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}
} public void del(Admin admin){
try {
PreparedStatement ps = con.prepareStatement("delete from admins where id=?");
ps.setInt(1, admin.getId());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}
} public void update(Admin admin){
try {
PreparedStatement ps = con.prepareStatement("update admins set email=?,first=?,last=? where id=?");
ps.setString(1,admin.getEmail());
ps.setString(2,admin.getFirst());
ps.setString(3,admin.getLast());
ps.setInt(4, admin.getId());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}
} public int totalCount(){
int total = 0;
try {
PreparedStatement ps = con.prepareStatement("select count(*) from admins");
ResultSet rs = ps.executeQuery();
if(rs.next()){
total = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return total;
} public void closeCon(){
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} }

时间过得好快,虽然学了几天ExtJs,可是后来没有用上,在这里还是总结一下基本用法。ExtJs很强大,远不止我总结的这些,要想学好并熟练运用还是要花费一番功夫的。不过建议初学者学习时要针对版本,每个版本的差异还是比较大的。

ExtJs之列表常用CRUD的更多相关文章

  1. redis学习-散列表常用命令(hash)

    redis学习-散列表常用命令(hash)   hset,hmset:给指定散列表插入一个或者多个键值对 hget,hmget:获取指定散列表一个或者多个键值对的值 hgetall:获取所欲哦键值以及 ...

  2. python列表常用内建方法

    python列表常用内建方法: abc = ['a',1,3,'a'] #abc.pop(1) #删除索引1的值.结果['a', 3] #abc.append([123]) #结果:['a', 1, ...

  3. Python语言学习:列表常用的方法

    python 列表常用的方法 1.append( ):用于在列表末尾添加新的对象 list.appent(obj) #obj:添加到列表末尾的对象 #!/usr/bin/python aList = ...

  4. python3 字符串与列表常用功能

    一.字符串常用功能 1. capitalize(),将字符串的首字母变成大写,其余全部置为小写:如果字符串中有多个单词,也只是将第一个单词的首字母置为大写:例: >>> name = ...

  5. python基础之列表常用操作及知识点小结

    列表(list) List(列表) 是 Python 中使用最频繁的数据类型.列表可以完成大多数集合类的数据结构实现.它支持字符,数字,字符串甚至可以包含列表(所谓嵌套).列表用[ ]标识,是pyth ...

  6. Python自动化开发(三):循环次数控制、常用数据类型、字符串格式化、列表常用操作、列表的后续操作

    计数器的作用可以在死循环中,符合条件的情况下做自动退出中断 #!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 2017/3/14 11:2 ...

  7. Python_列表常用操作

    %d   数字 %f    浮点 %s    字符串 字符串常用功能: .strip()   默认去掉字符串两边空格#或者在括号里注明去除什么 查看列表方法:dir(列表名) .append(元素): ...

  8. Extjs 项目中常用的小技巧,也许你用得着(3)

    几天没写了,接着继续, 1.怎么获取表单是否验证通过: form.isValid()//通过验证为true 2.怎样隐藏列,并可勾选: hidden: true, 如果是动态隐藏的话: grid.ge ...

  9. list列表常用操作

    1.创建列表.只要把逗号分隔的不同的数据项使用方括号括起来即可 List = ['wade','james','bosh','haslem'] 2.使用 range() 创建数字列表 numbers ...

随机推荐

  1. 【BZOJ】1984 月下“毛景树”

    [算法]树链剖分+线段树 [题解]线段树的区间加值和区间覆盖操作不能同时存在,只能存在一个. 修改:从根节点跑到目标区域路上的标记全部下传,打完标记再上传回根节点(有变动才需要上传). 询问:访问到目 ...

  2. Intersecting Lines (计算几何基础+判断两直线的位置关系)

    题目链接:http://poj.org/problem?id=1269 题面: Description We all know that a pair of distinct points on a ...

  3. centos6.5下安装svn并且实现多项目管理配置方案

    #安装SVN服务器 yum install subversion #在home下创建svn根目录 mkdir /home/svn #在 /home/svn下创建pro1 , pro2, pro3 三个 ...

  4. HTML中设置超链接字体 & 字体颜色

    定义链接样式 CSS为一些特殊效果准备了特定的工具,我们称之为“伪类”.其中有几项是我们经常用到的,下面我们就详细介绍一下经常用于定义链接样式的四个伪类,它们分别是: :link :visited : ...

  5. Angular2.0 基础: 环境搭建

    最近在学习Angular2的使用,其实看过Angular2 文档的都知道,相比于之前的Angular1,Angular2 的改动还是挺大的. 而对于‘angular2 的本地开发环境的搭建的中,我们首 ...

  6. AndroidStudio创建jinLibs文件夹

    在文件中的buildTypes节点下添加 sourceSets.main {          jniLibs.srcDir 'libs'      } 如图

  7. Mimikatz.ps1本地执行

    PS C:\Users\hacker> Get-ExecutionPolicy Restricted PS C:\Users\hacker> Set-ExecutionPolicy Unr ...

  8. 檢查 cpu 的全部 gpio 狀態及設定

    $ adb root # cat /sys/kernel/debug/gpio

  9. nodejs 优雅的连接 mysql

    1.mysql 及 promise-mysql nodejs 连接 mysql 有成熟的npm包 mysql ,如果需要promise,建议使用 promise-mysql: npm:https:// ...

  10. sqlserver2008 死锁解决方法及性能优化方法

    sqlserver2008 死锁解决方法及性能优化方法 原文: http://blog.csdn.net/kuui_chiu/article/details/48621939 十步优化SQL Serv ...