用ext2.0实现一个用户的增,删,改,查
1.在上一节中我们介绍了一些ext的基本用法,现在我们用ext来实现对一个用户的增删改查操作
可参考的代码如下:
jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'userList.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="extJS/resources/css/ext-all.css"> <script type="text/javascript" src="extJS/js/ext-base.js"></script> <script type="text/javascript" src="extJS/js/ext-all.js"></script> <link rel="stylesheet" type="text/css" href="extJS/resources/css/xtheme-purple.css"> </head> <body> <div id="win"> <div id="userGrid" style="height: 300px;"></div> </div> <div id="formWin"> <div id="form" align="center"></div> </div> <script type="text/javascript"> //用户列表 var renderSex=function(value){ if(value=='1'){ return "男"; }else if(value=='2'){ return "女"; }else{ return "保密"; } }; //构造列表节面的Grid var sm = new Ext.grid.CheckboxSelectionModel(); var cm = new Ext.grid.ColumnModel([ sm, new Ext.grid.RowNumberer(), {header:'编号', dataIndex:'id', sortable:true}, {header:'姓名', dataIndex:'name'}, {header:'年龄', dataIndex:'age'}, {header:'性别', dataIndex:'sex', renderer:renderSex}, {header:'描述', dataIndex:'descn'} ] ); var ds = new Ext.data.Store({ proxy:new Ext.data.HttpProxy({url:'userAction!list.action'}), reader:new Ext.data.JsonReader({ totalProperty:'totalProperty', root:'root', fields:[ {name:'id', mapping:'id', type:'string'}, {name:'name', mapping:'name', type:'string'}, {name:'age', mapping:'age', type:'int'}, {name:'sex', mapping:'sex', type:'string'}, {name:'descn', mapping:'descn', type:'string'} ] }) }); var grid=new Ext.grid.GridPanel({ el:'userGrid', store:ds, cm:cm, sm:sm, bbar:new Ext.PagingToolbar({ pageSize:10, store:ds, displayInfo:true, displayMsg:"显示第{0}条记录到第{1}条记录,共显示{2}条记录", emptyMsg:"没有记录" }) }); grid.render(); ds.load({params:{start:0,limit:10}}); //用户新增 function save(){ var form = createForm(); var formWin = createFormWin("用户新增", "新增", "userAction!add.action", form); formWin.show(); } //构造下拉列表 function createCombo(){ var sexData=[[1, '男'],[2, '女'], [3, '保密']]; var sexDs = new Ext.data.Store({ proxy: new Ext.data.MemoryProxy(sexData), reader: new Ext.data.ArrayReader({}, [ {name: 'id' }, {name: 'sex'} ]) }); sexDs.load(); var sexCmb = new Ext.form.ComboBox({ emptyText:'请选择性别', fieldLabel:'性别', store:sexDs, hiddenName:'user.sex', triggerAction:'all', displayField:'sex', mode:'local', editable:false, allowBlank:false, valueField:'id', width:210 }); return sexCmb; } //构造表单 function createForm(){ var sexCmb = createCombo(); var form = new Ext.form.FormPanel({ labelAlign:'center', labelWidth:50, title:'Form', frame:true, width:220, closeAction:'hide', shadow:true, items:[{xtype:'hidden', name:'user.id'},{fieldLabel:'姓名', name:'user.name',xtype:'textfield'}, {fieldLabel:'年龄', name:'user.age',xtype:'textfield'}, sexCmb, {fieldLabel:'描述', name:'user.descn',xtype:'textarea'} ] }); return form; } //构造表单窗体 function createFormWin(title, btnText, url, form){ var fwDiv = Ext.get('formWin'); var formWid = new Ext.Window({ el:fwDiv, layout:'fit', title:title, width:500, height:300, items:[form], buttons:[{text:btnText, handler:function(){ form.getForm().submit({ url:url, method:"POST", success:function(form, action){ formWid.close(); ds.reload(); }, failure:function(form, action){ Ext.Msg.alert("错误",action.result.errorMsg); } }); }}] }); return formWid; } //判读是否选择一条记录 function checkSingleSelect(){ if(grid.selModel.hasSelection()){ var records = grid.selModel.getSelections(); var recordsLen = records.length; if(recordsLen>1){ Ext.Msg.alert("提示", "只能选择一条记录"); return false; }else{ return true; } }else{ Ext.Msg.alert("提示", "请先选择一条记录"); return false; } } function load(){ } //用户修改 function edit(){ if(checkSingleSelect()){ var form = createForm(); var records = grid.getSelectionModel().getSelected(); var formWin = createFormWin("用户更新", "修改","userAction!edit.action", form); formWin.show(); form.getForm().setValues({ 'user.id':records.get("id"), 'user.name':records.get("name"), 'user.age':records.get("age"), 'user.sex':records.get("sex"), 'user.descn':records.get("descn") }); } } //用户删除 function remove(){ if(checkSingleSelect()){ var result = Ext.MessageBox.confirm("提示", "你是否确定删除该记录?", function(btn){ if(btn=='yes'){ var records = grid.getSelectionModel().getSelected(); var myCon = new Ext.data.Connection(); myCon.request({ url:'userAction!delete.action', params:{'deleteIds':records.get("id")}, method:'POST', success:function(r, o){ var a =Ext.decode(r.responseText); if(a.success){ ds.reload(); }else{ Ext.Msg.alert("错误",a.errorMsg); } }, failure:function(o, r){ Ext.Msg.alert("错误","删除失败!"); } }); } }, grid); } } //构造工具栏 var toolBar = new Ext.Toolbar({ buttons:[{text:'新增用户', handler:save }, {text:'修改用户', handler:edit }, {text:'删除用户', handler:remove }] }); //构造窗体 var win = new Ext.Window({ el:'win', title:'用户列表', layout:'fit', width:700, height:600, items:[grid], tbar:toolBar }); win.show(); </script> </body> </html>
java代码如下:
package com.baoz.extPro.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.baoz.extPro.dao.DAO; import com.baoz.extPro.dao.DAOImpl; import com.baoz.extPro.entity.User; import com.baoz.extPro.utils.ActionUtils; import com.baoz.extPro.utils.JsonUtils; import com.opensymphony.oscache.util.StringUtil; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private User user; private String deleteIds; private String s_name; private String s_age; private String link_id; public String getDeleteIds() { return deleteIds; } public void setDeleteIds(String deleteIds) { this.deleteIds = deleteIds; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String list() throws Exception { DAO dao = new DAOImpl(); StringBuffer hql = new StringBuffer(); hql.append("from User as u where 1=1 "); System.out.println("s_name="+s_name); System.out.println("s_age="+s_age); if(s_name!=null && !s_name.equals("")){ hql.append(" and u.name like '%"); hql.append(s_name); hql.append("%'"); } if(s_age!=null && !s_age.equals("")){ hql.append(" and u.age="); hql.append(s_age); } List list = dao.someList(hql.toString()); HttpServletRequest request = ServletActionContext.getRequest(); String start = request.getParameter("start"); String limit = request.getParameter("limit"); System.out.println("limit="+limit); Integer index = Integer.parseInt(start); Integer pageSize = Integer.parseInt(limit); System.out.println("index="+start); System.out.println("pageSize="+limit); StringBuffer json = new StringBuffer(); json.append("{"); json.append("totalProperty:").append(list.size()).append(", "); json.append("root:["); int size = list.size(); if (pageSize + index <= size) { size = pageSize + index; } for (int i = index; i < size; i++) { User user = (User) list.get(i); json.append("{id:'").append(user.getId()).append("', name:'") .append(user.getName()).append("', age:").append( user.getAge()).append(", sex:'").append( user.getSex()).append("', descn:'").append( user.getDescn()).append("'"); if (i == size - 1) { json.append("}"); } else { json.append("},"); } } json.append("]"); json.append("}"); HttpServletResponse response = ServletActionContext.getResponse(); ActionUtils.sendText(response, json.toString()); return null; } public String tree() throws Exception { StringBuffer json = new StringBuffer(); json.append("[").append(JsonUtils.json.toString()).append("]"); HttpServletResponse response = ServletActionContext.getResponse(); ActionUtils.sendText(response, json.toString()); return null; } public String add() { System.out.println("user=" + user); DAO dao = new DAOImpl(); HttpServletResponse response = ServletActionContext.getResponse(); try { dao.save(user); ActionUtils.sendText(response, "{success:true}"); } catch (Exception e) { e.printStackTrace(); ActionUtils.sendText(response, "{success:false, errorMsg:'添加" + user.getName() + "失败!'}"); } return null; } public String edit() { DAO dao = new DAOImpl(); HttpServletResponse response = ServletActionContext.getResponse(); try { dao.update(user); ActionUtils.sendText(response, "{success:true}"); } catch (Exception e) { e.printStackTrace(); ActionUtils.sendText(response, "{success:false, errorMsg:'修改" + user.getName() + "失败!'}"); } return null; } public String delete() { DAO dao = new DAOImpl(); HttpServletResponse response = ServletActionContext.getResponse(); try { String[] idArray = deleteIds.split(","); for (String id : idArray) { dao.delete(User.class, id); } ActionUtils.sendText(response, "{success:true}"); } catch (Exception e) { e.printStackTrace(); ActionUtils.sendText(response, "{success:false, errorMsg:'删除失败!'}"); } return null; } public String link(){ System.out.println("link_id="+link_id); return null; } public String getS_age() { return s_age; } public void setS_age(String s_age) { this.s_age = s_age; } public String getS_name() { return s_name; } public void setS_name(String s_name) { this.s_name = s_name; } public String getLink_id() { return link_id; } public void setLink_id(String link_id) { this.link_id = link_id; } }
出现的问题:
在实现这个效果的时候,虽然页面上没有报错,但是在页面上总是不能显示那个装载查询出来的数据
的GridPanel,后来经过仔细研究,原来是
<div id="win"><div id="userGrid" style="height: 300px;"></div></div>
这段代码中div的height没有设置。ext2.0就有这么一个缺陷。如果你不设置它的高度,它是显示不出来的。