extjs登录及crud

没使用mvc之前的extjs4.2登录及extjs4.2的crud代码。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="/mbs1/js/ext/resources/css/ext-all.css" />
<script type="text/javascript" src="/mbs1/js/ext/bootstrap.js"></script>
<script type="text/javascript" src="/mbs1/js/ext/locale/ext-lang-zh_CN.js"></script>
<!--定义全局JS变量-->
<script type="text/javascript">var GLOBAL_ROOT_PATH="/mbs1";</script>
<style type="text/css">
	html,body{
	height: 100%;
	width: 100%;
	margin: 0px;
	padding: 0px;	
	}
</style>
</head>
<body>
<script type="text/javascript">
Ext.onReady(function(){
	
	var win;
	
	Ext.define('com.xxx.model.user', {
	    extend: 'Ext.data.Model',
		alias : 'model.user',	    
		idProperty:'userId',
	    fields: [
	        {name: 'userId',     type: 'int'},
	        {name: 'loginName',      type: 'string'},
	        {name: 'realName',    type: 'string'},
	        {name: 'email',   type: 'string'},
	        {name: 'phone', type: 'string'},
	        {name: 'status',    type: 'int'}
	    ]  
	});	
	

	Ext.define('com.xxx.store.user', {
	    alias:'store.user',
	    extend: 'Ext.data.Store',
	    model: 'com.xxx.model.user',
	    proxy: {
	        type: "ajax",
	        url: GLOBAL_ROOT_PATH+"/user/listbypage",
	        actionMethods : {
				create : "POST",
				read : "POST",
				update : "POST",
				destroy : "POST"
			},
			api: {
				read: GLOBAL_ROOT_PATH+"/user/listbypage",
				create: 'bookCreate.php',
				update: GLOBAL_ROOT_PATH+"/user/edit",
				destroy: 'bookDestroy.php'
				},			
	        reader: {
	            type: "json",
	            root: 'listData',
	            totalProperty: 'totalRecordCount'
	        }
	    },
	    pageSize: 3,
	    sorters: [{
	            property: 'user_id',
	            direction: 'ASC'
	        }],
	    autoLoad: false
	});

	store_object=new com.xxx.store.user();
	store_object.loadPage(1);
	
	var mypagingtoolbar=Ext.create('Ext.toolbar.Paging',{
			store: store_object,     
			dock: 'bottom',  
			displayMsg: '显示 {0} - {1} 条,共计 {2} 条',
			emptyMsg: "没有数据",
			afterPageText: "页  共{0}页",
			beforePageText: "第",
			displayInfo: true
	});
	
		Ext.create('Ext.grid.Panel', {
		    title: '用户信息浏览',
		    tbar : [ {  
                xtype : 'button',  
                text : '新增',  
                handler : function(){
                	var add_form=Ext.create('com.xxx.view.user.addform');
                        win = new Ext.Window({
                         layout:'border',
                         title:'新增数据',
                         modal:true,
                            width:400,
                            height:200,
                            closeAction:'destroy',
                            plain: true,
                            items:[add_form]
                    });
                    win.down('form').getForm().reset();
                    win.show(this);		                    
                }  
            }],		    
		    store: store_object,
		    columnLines : true, 
		    forceFit : true,
		    columns: [
		        {text: '用户id',  dataIndex:'userId'},
		        {text: '登录名称',  dataIndex:'loginName'},
		        {text: '真实姓名',  dataIndex:'realName'},
		        {
		            xtype:'actioncolumn',
		            width:60,
		            items: [{
		                icon: GLOBAL_ROOT_PATH+'/css/img/edit.png',  // Use a URL in the icon config
		                tooltip: 'Edit',
		                handler: function(grid, rowIndex, colIndex) {
		                    var rec = grid.getStore().getAt(rowIndex);
		                    var edit_form=Ext.create('com.shinowit.view.user.editform');
		                        win = new Ext.Window({
		                        	title:'数据编辑',
									layout:'border',
		                            width:400,
		                            height:200,
		                            closeAction:'destroy',
		                            modal:true,
		                            plain: true,
		                            items:[edit_form]
		                    });
		                    win.down('form').loadRecord(rec);
		                    win.show(this);
		                }
		            },{
		                icon:GLOBAL_ROOT_PATH+ '/css/img/delete.gif',
		                tooltip: 'Delete',
		                handler: function(grid, rowIndex, colIndex) {
		                    var rec = grid.getStore().getAt(rowIndex);
		                    Ext.MessageBox.confirm("提示","您确定要删除这些信息吗?",function(button,text){ 
		                    		if (button=='yes'){
		    		                    Ext.Ajax.request({
		    		                        url: GLOBAL_ROOT_PATH+'/user/del',
		    		                        params: {
		    		                            id: rec.get('userId')
		    		                        },
		    		                        success: function(response){
		    		                            var text = response.responseText;
		    		                            var jsonObj=eval("("+text+")");
		    		                            if (true==jsonObj.success){
		    		                            	  Ext.Msg.alert('成功', jsonObj.msg);
		    		                            	  Ext.getStore(store_object).reload();
		    		                            }else{
		    		                            	  Ext.Msg.alert('失败', jsonObj.msg);
		    		                            }
		    		                        }
		    		                    });
		                    		}
		                    		});		                    
		                }
		            }]
		        }
		    ],
		    width: '100%',
		    height:'100%',
		    dockedItems: [  
		    	mypagingtoolbar
		    ],
		    renderTo: Ext.getBody()
		});		
		
		
		 Ext.define('com.xxx.view.user.editform', {
			 extend:'Ext.form.FormPanel',
				bodyStyle:'padding-top:20px;padding-left:20px;',
		        defaultType:'textfield',
		        labelAlign:'right',
			    width:'auto',
		        height : 150,
		        frame : true,
				buttonAlign:'center', 
				defaults : {
		            allowBlank : false,
		            autowidth : true,
		            labelAlign:'right',
		            width : 399
		        },
		      items:[
		      {xtype: 'hiddenfield',name: 'userId', value: ''},
		      {fieldLabel:'登录名称',name:'loginName',height:20,blankText:'请输入登录名称'},
		      {fieldLabel:'真实姓名',name:'realName', height:20,blankText:'请输入真实姓名'}
		      ],
		      buttons:[
		      {xtype:'button',text:'重输',handler:function(){this.up("form").getForm().reset();}},
		      {xtype:'button',text:'保存',handler: function() {
		            var form = this.up('form').getForm();
		            if (form.isValid()) {
		            	 form.submit({
		 			        url:GLOBAL_ROOT_PATH+'/user/edit',
		 					waitTitle : '提示',//标题
		      				waitMsg : '正在提交数据请稍候...',//提示信息                	
		                     success: function(form, action) {
		                    	 if (true==action.result.success){
				                        Ext.Msg.alert('成功', action.result.msg);
				                        //var start=mypagingtoolbar.cursor;  //得到当前记录指针
				                        //var limit=mypagingtoolbar.pageSize; //得到每页要显示的记录数 
				                        //Ext.getStore(store_object).load({params:{start:start,limit:limit}});
				                        Ext.getStore(store_object).reload();
				                        win.close();                            //关闭编辑框
		                    	 }else{
				                        Ext.Msg.alert('错误', action.result.msg);
		                    	 }
		                     },
		                     failure: function(form, action) {
		                         Ext.Msg.alert('错误', action.result.msg);
		                     }
		                 });		            	
		            	
		            	//record =form.getRecord(),            //获取表单数据元素
		                //values = form.getValues();            //获取该表单值
		            	//record.set(values);                        //修改当前的值
			            //Ext.getStore(store_object).sync();
		            	//record.commit();
  			            //win.close();                            //关闭编辑框
		            }
		        }}
		      ]
		  });
		  
		  Ext.define('com.xxx.view.user.addform',{
			    extend:'Ext.form.FormPanel',
				bodyStyle:'padding-top:5px;padding-left:5px;',
		        defaultType:'textfield',
		        labelAlign:'right',
			    width:'auto',
		        height : 150,
		        width:390,
		        frame : true,
				buttonAlign:'center', 
				defaults : {
		            allowBlank : false,
		            autowidth : true,
		            labelAlign:'right',
		            width : 299
		        },
		      items:[
		      {xtype: 'hiddenfield',name: 'userId', value: ''},
		      {fieldLabel:'登录名称',name:'loginName',height:20,blankText:'请输入登录名称'},
		      {fieldLabel:'真实姓名',name:'realName', height:20,blankText:'请输入真实姓名'}
		      ],
		      buttons:[
		      {xtype:'button',text:'重输',handler:function(){this.up("form").getForm().reset();}},
		      {xtype:'button',text:'保存',handler: function() {
		            var form = this.up('form').getForm();
		            if (form.isValid()) {
		            	
		            	 form.submit({
		 			        url:GLOBAL_ROOT_PATH+'/user/add',
		 					waitTitle : '提示',//标题
		      				waitMsg : '正在提交数据请稍候...',//提示信息                	
		                     success: function(form, action) {
		                    	 if (true==action.result.success){
				                        Ext.Msg.alert('成功', action.result.msg);
				                        Ext.getStore(store_object).reload();
				                        win.close();                            //关闭编辑框
		                    	 }else{
				                        Ext.Msg.alert('错误', action.result.msg);
		                    	 }
		                     },
		                     failure: function(form, action) {
		                         Ext.Msg.alert('错误', action.result.msg);
		                     }
		                 });		            	
		            	
		            	//record =form.getRecord(),            //获取表单数据元素
		                //values = form.getValues();            //获取该表单值
		            	//record.set(values);                        //修改当前的值
			            //Ext.getStore(store_object).sync();
		            	//record.commit();
			            //win.close();                            //关闭编辑框
		            }
		        }}
		      ]
		  });
});
</script>
</body>
</html>

 

 

package com.xxx.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xxx.dao.mapper.SysUserMapper;
import com.xxx.model.SysUser;
import com.xxx.model.SysUserCriteria;

@Controller
@RequestMapping(value="/user")
public class UserController {
	private static final Logger logger = Logger.getLogger(UserController.class);

	@Resource
	private SysUserMapper sys_user_dao;
	
	@RequestMapping(value="/listbypage")
	@ResponseBody
	public Map<String,Object> listByPage(@RequestParam("start") int start,@RequestParam("limit") int pageSize,@RequestParam("page") int pageIndex){
		Map<String,Object> result=new HashMap<String,Object>();
		
		SysUserCriteria ex=new SysUserCriteria();
		ex.setPageSize(pageSize);
		ex.setPageIndex(pageIndex);
		ex.setOrderByClause("user_id");
	
		
		List<SysUser> list_data=null;
		try {
			list_data=sys_user_dao.selectPage(ex);
			result.put("listData", list_data);
			if (logger.isDebugEnabled()){
				logger.debug("取得分页结果记录行数:"+list_data.size());
			}
		} catch (Exception e) {
			if (logger.isDebugEnabled()){
				logger.error(e.getMessage(), e);
			}
			result.put("success", false);
			result.put("msg", "保存失败!数据库操作异常!");
			result.put("totalRecordCount", 0);
			result.put("listData", list_data);
			return result;
		}
		
		 //取得满足查询条件的记录总数
		try {
			int record_count=sys_user_dao.countByExample(ex);
			result.put("totalRecordCount", record_count);
		} catch (Exception e) {
			result.put("totalRecordCount", 0);
			if (logger.isDebugEnabled()){
				logger.error(e.getMessage(), e);
			}
		}
		
		return result;
	}

	@RequestMapping(value="/add")
	@ResponseBody
	public Map<String,Object> add(SysUser user){
		Map<String,Object> result=new HashMap<String,Object>();
		
		int rec_changed=0;
		try {
			 rec_changed=sys_user_dao.insert(user);
		} catch (Exception e) {
			if (logger.isDebugEnabled()){
				logger.error(e.getMessage(), e);
			}
			result.put("success", false);
			result.put("msg", "保存失败!数据库操作异常!");
			return result;
		}
		if (rec_changed>0){
			result.put("success", true);
			result.put("msg", "保存成功!");
		}else{
			result.put("success", false);
			result.put("msg", "保存失败!");
		}
		return result;
	}
	
	
	@RequestMapping(value="/edit")
	@ResponseBody
	public Map<String,Object> edit(SysUser user){
		Map<String,Object> result=new HashMap<String,Object>();
		
		int rec_changed=0;
		try {
			 rec_changed=sys_user_dao.updateByPrimaryKey(user);
		} catch (Exception e) {
			if (logger.isDebugEnabled()){
				logger.error(e.getMessage(), e);
			}
			result.put("success", false);
			result.put("msg", "保存失败!数据库操作异常!");
			return result;
		}
		if (rec_changed>0){
			result.put("success", true);
			result.put("msg", "保存成功!");
		}else{
			result.put("success", false);
			result.put("msg", "保存失败!");
		}
		return result;
	}


	@RequestMapping(value="/del")
	@ResponseBody
	public Map<String,Object> del(@RequestParam("id") Integer userId){
		Map<String,Object> result=new HashMap<String,Object>();
		
		int rec_changed=0;
		try {
			 rec_changed=sys_user_dao.deleteByPrimaryKey(userId) ;
		} catch (Exception e) {
			if (logger.isDebugEnabled()){
				logger.error(e.getMessage(), e);
			}
			result.put("success", false);
			result.put("msg", "删除失败!数据库操作异常!");
			return result;
		}
		if (rec_changed>0){
			result.put("success", true);
			result.put("msg", "删除成功!");
		}else{
			result.put("success", false);
			result.put("msg", "删除失败!");
		}
		return result;
	}
	
}


 

以下为登录的extjs

 

Ext.onReady(function(){
 Ext.QuickTips.init();
 Ext.form.Field.prototype.msgTarget = 'side';
 //以下自定义一个vtype输入校验规则
 Ext.apply(Ext.form.field.VTypes, {
                  //使用正则表达式
                  validcode:function(value,field){
                    var regEx=/^\d{4}$/; //4位数字              
                    return regEx.test(value);               
                  },
                  validcodeText:"请输入正确的验证码",
                  validcodeMask:/[0-9-]/  //限制键盘的输入
 });
   
  var login_form=new Ext.create('Ext.form.FormPanel',{
		bodyStyle:'padding-top:20px;padding-left:20px;',
        defaultType:'textfield',
        labelAlign:'right',
	    width:'auto',
        height : 150,
        frame : true,
		buttonAlign:'center', 
		defaults : {
            allowBlank : false,
            autowidth : true,
            labelAlign:'right',
            width : 210,
            vtype:'alphanum' //缺省只能输入字母和数字
        },
      items:[
      {fieldLabel:'登录名称',id:'loginName',name:'loginName',height:20,blankText:'请输入登录名称'},
      {fieldLabel:'登录密码',id:'loginPass',name:'loginPass',inputType:'password', height:20,blankText:'请输入登录密码'},
      {fieldLabel:'校验码',id:'validCode',name:'validCode',vtype:'validcode', width : 180,height:20,blankText:'请输入校验码',minLength:4,maxLength:4,minLengthText:'校验码不能少于4个',maxLengthText:'校验码不能多于4个数字'}
      ],
      buttons:[
      {xtype:'button',text:'重输',handler:function(){this.up("form").getForm().reset();}},
      {xtype:'button',text:'登录',handler: function() {
            var form = this.up('form').getForm();
            if (form.isValid()) {
                form.submit({
			        url:GLOBAL_ROOT_PATH+'/login/checklogin',
					waitTitle : '提示',//标题
     				waitMsg : '正在提交数据请稍候...',//提示信息                	
                    success: function(form, action) {
                    	window.location.href=action.result.mainurl;
                       //Ext.Msg.alert('成功', action.result.msg);
                    },
                    failure: function(form, action) {
                        Ext.Msg.alert('错误', action.result.msg);
                    }
                });
            }
        }}
      ]
  });
  
  var login_window=new Ext.create('Ext.window.Window',{
		title:'用户登录',
	    width : 300,
	    collapsible:false,
	    closable:false,
	    resizable:false,
	    modal:true,
	    draggable:false,
	    shadow :true,
    items:[login_form]
  });
  login_window.show();
 //创建验证码
 Ext.core.DomHelper.insertAfter( Ext.get('validCode'),   {
               tag: 'img',
               id:'checkimg',
               name:'checkimg',
               src: GLOBAL_ROOT_PATH+'/html/validcode.jsp?id='+new Date().getTime(),  
               align: 'absbottom',
               style: 'position: absolute;left: 200px;top: 70px;'
   } );
   Ext.get('checkimg').on({
   	'click':{fn:function(){
       this.src=GLOBAL_ROOT_PATH+'/html/validcode.jsp?id='+new Date().getTime();
   }}});
});

 

你可能感兴趣的:(ExtJs)