ExtJs之列表常用CRUD
前端代码:
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的更多相关文章
- redis学习-散列表常用命令(hash)
redis学习-散列表常用命令(hash) hset,hmset:给指定散列表插入一个或者多个键值对 hget,hmget:获取指定散列表一个或者多个键值对的值 hgetall:获取所欲哦键值以及 ...
- python列表常用内建方法
python列表常用内建方法: abc = ['a',1,3,'a'] #abc.pop(1) #删除索引1的值.结果['a', 3] #abc.append([123]) #结果:['a', 1, ...
- Python语言学习:列表常用的方法
python 列表常用的方法 1.append( ):用于在列表末尾添加新的对象 list.appent(obj) #obj:添加到列表末尾的对象 #!/usr/bin/python aList = ...
- python3 字符串与列表常用功能
一.字符串常用功能 1. capitalize(),将字符串的首字母变成大写,其余全部置为小写:如果字符串中有多个单词,也只是将第一个单词的首字母置为大写:例: >>> name = ...
- python基础之列表常用操作及知识点小结
列表(list) List(列表) 是 Python 中使用最频繁的数据类型.列表可以完成大多数集合类的数据结构实现.它支持字符,数字,字符串甚至可以包含列表(所谓嵌套).列表用[ ]标识,是pyth ...
- Python自动化开发(三):循环次数控制、常用数据类型、字符串格式化、列表常用操作、列表的后续操作
计数器的作用可以在死循环中,符合条件的情况下做自动退出中断 #!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 2017/3/14 11:2 ...
- Python_列表常用操作
%d 数字 %f 浮点 %s 字符串 字符串常用功能: .strip() 默认去掉字符串两边空格#或者在括号里注明去除什么 查看列表方法:dir(列表名) .append(元素): ...
- Extjs 项目中常用的小技巧,也许你用得着(3)
几天没写了,接着继续, 1.怎么获取表单是否验证通过: form.isValid()//通过验证为true 2.怎样隐藏列,并可勾选: hidden: true, 如果是动态隐藏的话: grid.ge ...
- list列表常用操作
1.创建列表.只要把逗号分隔的不同的数据项使用方括号括起来即可 List = ['wade','james','bosh','haslem'] 2.使用 range() 创建数字列表 numbers ...
随机推荐
- bzoj 3196/ Tyvj 1730 二逼平衡树 (线段树套平衡树)
3196: Tyvj 1730 二逼平衡树 Time Limit: 10 Sec Memory Limit: 128 MB[Submit][Status][Discuss] Description ...
- 单词转换成向量形式 word2vec
word2vec(word to vector)是一个将单词转换成向量形式的工具.可以把对文本内容的处理简化为向量空间中的向量运算,计算出向量空间上的相似度,来表示文本语义上的相 似度.word2ve ...
- 自定义ToolBar
一.Toolbar的简介 Toolbar 是 android 5.0 引入的一个新控件,Toolbar出现之前,我们很多时候都是使用ActionBar以及ActionActivity实现顶部导航栏的, ...
- Android中自定义属性attr.xml的格式详解
1. reference:参考某一资源ID. (1)属性定义: <declare-styleable name = "名称"> ...
- python 学习笔记 sqlalchemy
数据库表是一个二维表,包含多行多列.把一个表的内容用Python的数据结构表示出来的话,可以用一个list表示多行,list的每一个元素是tuple,表示一行记录,比如,包含id和name的user表 ...
- 【openjudge】C15C Rabbit's Festival CDQ分治+并查集
题目链接:http://poj.openjudge.cn/practice/C15C/ 题意:n 点 m 边 k 天.每条边在某一天会消失(仅仅那一天消失).问每一天有多少对点可以相互到达. 解法:开 ...
- MariaDB 层常用业务
前言 - 简单准备一下前戏 前面写过几篇mariadb 数据的随笔, 多数偏C/C++层面. 这次分享一下平时开发中, 处理的一些数据层面的业务. 对于MariaDB, 不做过多介绍. 如果你有U ...
- 网站服务器压力Web性能测试(1):Apache Bench:Apache自带服务器压力测试工具
一个网站或者博客到底能够承受多大的用户访问量经常是我们在用VPS或者独立服务器搭建网站了最关心的问题,还有不少人喜欢对LNMP或者LAMP进行一些优化以便提高Web性能,而优化后到底有多大的效果,就需 ...
- Leetcode 之Regular Expression Matching(31)
正则表达式的匹配,还是挺难的.可根据下一个字符是不是*分为两种情况处理,需要考虑多种情况. bool isMatch(const char *s, const char *p) { if (*p == ...
- 欢迎访问新博客aiyoupass.com
新博客基本搭建好了,欢迎访问.aiyoupass.com