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很强大,远不止我总结的这些,要想学好并熟练运用还是要花费一番功夫的。不过建议初学者学习时要针对版本,每个版本的差异还是比较大的。

由于lazarus的例子: lazarus\fpc\2.6.0\source\packages\fcl-web\examples\webdata\demo 用的extjs是3.4版,在新的extjs4.2环境下不能运行,费了好大劲,终于搞定。期间到laz英文论坛提问,可能跟我英文差有关吧,一个回答的都没有。搞定后,版主又要我进行了“ open a new issue in the bugtracker and add a diff with the changes ”。本着互助、共享的原则,整个东西放到lazarus文社区论坛,欢迎大家不断改善源码,提高性能,并且将改善后的源码进行共享。 我的环境:winxp,lazarus1.1,fpc2.6.0,apache2.2,extjs4.2。 不要犯怵,安装配置很简单,运行这个demo一行代码都不需要编写。后面我会详细讲安装运行方法。 安装配置: 1、安装Apache。下载地址:http://www.fayea.com/apache-mirror//httpd/binaries/win32/httpd-2.2.22-win32-x86-openssl-0.9.8t.msi 其他版本我没试过,高版本的应该可以。 我安装到了D:\apache2.2 2、下载安装Extjs4.2。下载地址:http://cdn.sencha.io/ext-4.2.0-beta.zip?ref=extjs.org.cn 下载后,解压缩,文件夹复制到 D:\apache2.2\htdocs\,然后改名为Ext。 3、下载附件。 原来的lazarus demo 源码未做任何修改,直接编译即可。编译之前需要安装weblaz和lazwebextra两个包。 本文附件已经有extgrid.exe,可以直接使用。 将extgrid.exe和users.dbf复制到 apache2.2\cgi-bin 目录下。 将附件其余文件复制到 apache2.2\htdocs\demodbf 目录下。 好了,全部配置完成。 4、启动Apache,访问:http://localhost/demodbf/extgrid-json.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值