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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。