ExtJS & GTGrid 简单用户管理



ExtJS & GTGrid 简单用户管理前段学了小胖的GTGrid,很方便实用。最近在学习Extjs.
做了个CRUD的Demo,包括Extjs版和GTGrid版,做的比较
粗糙,希望对大家有一些帮助。

部分源码:

<%@ page language=”java” pageEncoding=”GBK”%>
<%@taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c”%>
<c:set var=”ctx” value=”${pageContext.request.contextPath}”/>
<html>
  <head>
      <title>用户管理首页</title>
<link rel=”stylesheet” type=”text/css” href=”js/ext-2.2/resources/css/ext-all.css” />
<script type=”text/javascript” src=”js/ext-2.2/adapter/ext/ext-base.js”></script>
<script type=”text/javascript” src=”js/ext-2.2/ext-all.js”></script>
<style type=”text/css”>
.x-panel-body p {
        margin:5px;
    }
    .x-column-layout-ct .x-panel {
        margin-bottom:5px;
    }
    .x-column-layout-ct .x-panel-dd-spacer {
        margin-bottom:5px;
    }
    .settings {
        background-image:url(js/ext-2.2/shared/icons/fam/folder_wrench.png) !important;
    }
    .nav {
        background-image:url(js/ext-2.2/shared/icons/fam/folder_go.png) !important;
    }

.icon-grid {
    background-image: url(js/ext-2.2/shared/icons/fam/grid.png) !important;
}

#button-grid .x-panel-body {
    border: 1px solid #99bbe8;
    border-top: 0 none;
}

.add {
    background-image: url(js/ext-2.2/shared/icons/fam/add.gif) !important;
}

.option {
    background-image: url(js/ext-2.2/shared/icons/fam/plugin.gif) !important
        ;
}

.remove {
    background-image: url(js/ext-2.2/shared/icons/fam/delete.gif) !important
        ;
}

.save {
    background-image: url(js/ext-2.2/shared/icons/save.gif) !important;
}
</style>
<script>
    <!–
    Ext.onReady(function()
    {
        /**Grid相关**/
        Ext.QuickTips.init();
        Ext.form.Field.prototype.msgTarget=’side’;
        var newFormWin; //form窗口容器
        var form1; //添加用户的form
        var form2;; //修改用户的form

        //侧边栏状态的记录
        Ext.state.SessionProvider = Ext.extend(Ext.state.CookieProvider, {
        readCookies : function(){
                if(this.state){
                    for(var k in this.state){
                        if(typeof this.state[k] == ’string’){
                            this.state[k] = this.decodeValue(this.state[k]);
                        }
                    }
                }
                return Ext.apply(this.state || {}, Ext.state.SessionProvider.superclass.readCookies.call(this));
            }
        });

        var xg = Ext.grid;

        var jsonReader = new Ext.data.JsonReader( {
            root : ’list’,  //返回的数据集合
            totalProperty : ’totalCount’, //总记录数
            successProperty : ’@success’ //成功标记
        }, [ {
            name : 'id', //grid中的dataIndex
            mapping : 'id', //返回的数据中的字段名
            type : 'int' //类型,默认为string类型
        }, {
            name : 'username',
            mapping : 'username'
        }, {
            name : 'age',
            mapping : 'age',
            type : 'int'
        },
        {
            name : 'ramark',
            mapping : 'remark'
        }]);

        // Store
        var ds = new Ext.data.Store( {
            proxy : new Ext.data.HttpProxy( {
                url : ’${ctx}/UserServlet?method=getAll’
            }),
            reader : jsonReader
        });
        ds.setDefaultSort(‘id’, ’asc’);


    /**
    ***CRUD Grid
    ****/

    //自定义的checkbox列选择
    var sm = new xg.CheckboxSelectionModel({
        listeners: //添加监听器
        {
          //行选择事件
          rowselect : function (sm, rowIndex, keep, rec) //行选中事件
          {
                //得到ext组件用Ext.getCmp(‘id’)
                var btn = Ext.getCmp(‘tbar1′);
                //选择数量大于2,禁用修改按钮
                if(sm.getCount() != 1)
                {
                      btn.disable();
                }
                else
                {
                    btn.enable();
                }
          },
          //取消选择事件
          rowdeselect : function (sm, rowIndex, keep, rec) //行选中事件
          {
                //得到ext组件用Ext.getCmp(‘id’)
                var btn = Ext.getCmp(‘tbar1′);
                //数量等于1启动修改按钮
                if(sm.getCount() == 1)
                {
                      btn.enable();
                }
                else
                {
                      btn.disable();
                }
          }
        }


    });

    //初始化Grid
    var grid = new xg.GridPanel({
        id:’user-grid’,
        width:780,
        height:450,
        frame:true,
        title:’简易用户管理’,
        iconCls:’icon-grid’,
        hidden: true,
        store: ds, //数据仓库
        renderTo: document.body,
        //列
        cm: new xg.ColumnModel([
            sm,
            {id:'id',header: "索引", width: 40, sortable: true, dataIndex: 'id'},
            {header: "用户名", width: 20, sortable: true,  dataIndex: 'username'},
            {header: "年龄", width: 20, sortable: true, dataIndex: 'age'},
            {header: "备注", width: 20, sortable: true, dataIndex: 'remark'}
        ]),

        sm: sm,

        viewConfig: {
            forceFit:true
        },
        //分页工具栏
        bbar : new Ext.PagingToolbar({
                pageSize : 10,
                store : ds,
                displayInfo : true,
                displayMsg : ’显示 {0}-{1}条 / 共 {2} 条’,
                emptyMsg : ”无数据。”
            }),

        //上置内嵌工具栏(按钮)
        tbar:[{
            text:'添加',
            tooltip:'添加一行新数据',
            iconCls:'add',
            handler : function()
            {
                add();
            }
        }, '-', {
            text:'修改',
            tooltip:'修改一条数据',
            iconCls:'option',
            id : 'tbar1',
            handler : function()
            {
                modify();
            }
        },'-',{
            text:'删除',
            tooltip:'删除数据',
            iconCls:'remove',
            handler : function()
            {
                remove();
            }
        }]

    });

    //加载数据
    ds.load({params:{start:0, limit:10}});
    //渲染Grid
    grid.render();

        //添加用户的函数
          var add = function()
          {
                newFormWin = new Ext.Window({
                    layout : ’fit’,
                    width : 400,
                    height : 300,
                    closeAction : ’hide’,
                    plain : true,
                    title : ’用户管理’,
                    items : form1

                });
            newFormWin.show();
          }

        //修改用户的函数
          var modify = function()
          {
            var _record = grid.getSelectionModel().getSelected();
            if (!_record)
            {
                Ext.Msg.alert(‘请选择要修改的一项!’);
            }
            else
            {
                myFormWin();
                form2.form.load
                ({
                    url : ’${ctx}/UserServlet?method=getById&id=’+ _record.get(‘id’),
                    waitMsg : ’正在载入数据‘,

                    failure : function() {
                        Ext.Msg.alert(‘载入失败’);
                    },
                    success : function() {
                        //Ext.Msg.alert(‘载入成功!’);
                    }
                });
            }
        }
        //修改用户的窗体
        var myFormWin = function() {
                newFormWin = new Ext.Window({
                    layout : ’fit’,
                    width : 400,
                    height : 300,
                    closeAction : ’hide’,
                    plain : true,
                    title : ’修改用户’,
                    items : form2
                });
            newFormWin.show(”);
        }

        /*注意JsonReader要放在Form上面,数据的加载顺序问题*/
        var jsonFormReader = new Ext.data.JsonReader( {
            root : ’list’,
            totalProperty : ’totalCount’,
            successProperty : ’@success’
        }, [
        {
            name : 'id',
            mapping : 'id',
            type : 'int',
        },
         {
            name : 'username',
            mapping : 'username'
        }, {
            name : 'age',
            mapping : 'age',
            type : 'int'
        }, {
            name : 'remark',
            mapping : 'remark'
        }]);

        //添加用户的Form
          form1 = new Ext.FormPanel({
            labelWidth : 75,
            frame : true,
            title : ’添加用户’,
            bodyStyle : ’padding:5px 5px 0′,
            width : 350,
            waitMsgTarget : true,
            url : ’${ctx}/UserServlet?method=save’,
            defaults :
            {
                width : 230
            },
            defaultType : ’textfield’,
            items : [
            {
                fieldLabel : '用户名',
                name : 'username', //后台得到数据用
                allowBlank : false,
                blankText : '用户名不能为空'
            }, {
                xtype : 'numberfield',
                maxValue : 100,
                maxText : '年龄不能超过100岁',
                minValue : 1,
                minText : '年龄不能小于1岁',
                fieldLabel : '年龄',
                name : 'age',
                allowBlank : false,
                blankText : '年龄不能为空'
            }, new Ext.form.TextArea( {
                fieldLabel : '备注',
                name : 'remark',
                growMin : 234,
                maxLength : 50,
                maxLengthText : '最大长度不能超过50个字符!'
            })],

            buttons : [ {
                text : '保存',
                disabled : false,
                handler : function()
                {

                    if(form1.form.isValid())
                    {
                        form1.form.submit(
                        {
                            url : '${ctx}/UserServlet?method=save',
                            success : function(from, action)
                            {
                                Ext.Msg.alert('添加用户成功!');
                                ds.load({
                                    params : {
                                        start : 0,
                                        limit : 10
                                    }
                                });
                            },
                            failure : function(form, action) {
                                Ext.Msg.alert('添加用户失败!');
                            },
                            waitMsg : '正在保存数据,稍后'
                        });
                        newFormWin.hide();
                    }
                    else
                    {
                        Ext.Msg.alert('请确认您已经的信息是否已经填写成功!');
                    }
                }
            }, {
                text : '取消',
                handler : function()
                {
                     form1.form.reset();
                }
            }]
        });

        //修改用户的Form
          form2 = new Ext.FormPanel({
            labelWidth : 75,
            frame : true,
            title : ’修改用户’,
            bodyStyle : ’padding:5px 5px 0′,
            width : 350,
            waitMsgTarget : true,
            url : ’${ctx}/UserServlet?method=update’,
            reader : jsonFormReader, //为Form指定reader,修改用
            defaults :
            {
                width : 230
            },
            defaultType : ’textfield’,
            items : [
            {
                xtype: 'hidden',
                name : 'id'
            },
            {
                fieldLabel : '用户名',
                name : 'username', //后台得到数据用
                allowBlank : false,
                blankText : '用户名不能为空'
            }, {
                xtype : 'numberfield',
                maxValue : 100,
                maxText : '年龄不能超过100岁',
                minValue : 1,
                minText : '年龄不能小于1岁',
                fieldLabel : '年龄',
                name : 'age',
                allowBlank : false,
                blankText : '年龄不能为空'
            }, new Ext.form.TextArea( {
                fieldLabel : '备注',
                name : 'remark',
                growMin : 234,
                maxLength : 50,
                maxLengthText : '最大长度不能超过50个字符!'
            })],

            buttons : [ {
                text : '修改',
                disabled : false,
                handler : function()
                {

                    if(form2.form.isValid())
                    {
                        form2.form.submit(
                        {
                            success : function(from, action)
                            {
                                Ext.Msg.alert('修改用户成功!');
                                ds.load({
                                    params : {
                                        start : 0,
                                        limit : 10
                                    }
                                });
                            },
                            failure : function(form, action) {
                                Ext.Msg.alert('修改用户失败!');
                            },
                            waitMsg : '正在保存数据,稍后'
                        });
                        newFormWin.hide();
                    }
                    else
                    {
                        Ext.Msg.alert('请确认您已经的信息是否已经填写成功!');
                    }
                }
            }, {
                text : '取消',
                handler : function()
                {
                     form2.form.reset();
                }
            }]
        });

        //删除事件
        var remove = function()
        {

            var _record = grid.getSelectionModel().getSelected();
            if (_record)
            {
                Ext.MessageBox.confirm(‘确认删除’, ’你确认要删除选择的数据吗?’, function(btn)
                {
                    if (btn == ”yes”) {
                        var m = grid.getSelections();
                        var jsonData = ”";
                        for (var i = 0, len = m.length;i < len; i++)
                        {
                            var ss = m[i].get(“id”); //用户id , ”id” 字段名
                            if (i == 0) {
                                jsonData = jsonData + ss;
                            } else {
                                jsonData = jsonData + ”,” + ss;
                            }
                            //在数据源里删除
                            ds.remove(m[i]);
                            //删除数据库相应记录
                            Ext.Ajax.request({
                               url: ’${ctx}/UserServlet?method=remove&id=’+ss
                            });
                        }

                        ds.load({
                            params : {
                                start : 0,
                                limit : 10,
                                delData : jsonData
                            }
                        });


                    }
                });
            }
            else
            {
                Ext.Msg.alert(‘请选择要删除的数据项!’);
            }
        };
    /***/
    Ext.state.Manager.setProvider
    ( new Ext.state.SessionProvider({state: Ext.appState}));

        // tabs for the center
        var tabs = new Ext.TabPanel({
            region    : ’center’,
            margins   : ’3 3 3 0′,
            activeTab : 0,
            defaults  : {
                autoScroll : true
            },
            items     : [{
                title    : 'ExtJS版',
                contentEl: 'user-grid' //要填充的html id
             },{
                title    : 'GTGrid版',
                html     : 'GTGrid暂不支持与Extjs的整合(window),<a href="${ctx}/gt.jsp">点此显示我做的例子</>'
             },{
                title    : '更多关注',
                html     : '更多内容可关注<a href="http://www.blogjava.net/supercrsky">我的博客</a>'
            }]
        });

        // Panel for the west
        var nav = new Ext.Panel({
            title       : ’菜单目录’,
            region      : ’west’,
            split       : true,
            width       : 200,
            collapsible : true,
            margins     : ’3 0 3 3′,
            cmargins    : ’3 3 3 3′,
            layout:        ’accordion’,
                layoutConfig:{
                    animate:true
                },
             items: [{
                    html: Ext.example.shortBogusMarkup,
                    title:'用户管理',
                    autoScroll:true,
                    border:false,
                    iconCls:'nav'
                },{
                    title:'用户配置',
                    html: Ext.example.shortBogusConfig,
                    border:false,
                    autoScroll:true,
                    iconCls:'settings'
                }]
        });

        var win = new Ext.Window({
            title    : ’用户管理微型系统’,
            closable : true,
            maximizable : true,
            minimizable : true,
            width    : ’100%’,
            height   : ’100%’,
            plain    : true,
            layout   : ’border’,
            closable : false,
            items    : [nav, tabs]
        });

        win.show();
        win.maximize();

});
    –>
</script>
  </head>
  <body>&nbsp;
  <!– 侧边栏使用的js –>
  <script type=”text/javascript” src=”js/ext-2.2/shared/examples.js”></script>
  </body>
</html>

完整的源码下载点此下载