標籤:extjs ext grid的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 }]});//構造storevar 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