• [Extjs] Ext4 Ext.grid.Panel 分页实现(mybatis 分页插件-PageHelper 使用)


    先看图:

    页面js代码:

     var userStore=Ext.create('Ext.data.Store', {
    	    storeId:'userStore',
    	    fields:['uname', 'email', 'phone','regIp','regTime'],
    	    proxy: {
    	        type: 'ajax',
    	        url:'${pageContext.request.contextPath}/back/user/userList.do',
    	        reader: {
    				// 設置 json樣式
    	            type: 'json',
    				rootProperty:"rows",
    				totalProperty:"total"
    	        }
    	    },
    	    autoLoad: true,
    	    pageSize:10 //每页记录数默认25
    	});
    
     userStore.load({
    	 params: {
    		 start: 0,
    		 limit: 10
    	 }
     });
     
     var ckm=Ext.create("Ext.selection.CheckboxModel");
      Ext.onReady(function(){
    		Ext.create('Ext.grid.Panel', {
    		    title: '用户信息',
    		    id:'userGridPanel',
    		    selModel:ckm,
    		    store:userStore,// Ext.data.StoreManager.lookup('simpsonsStore'),
    		    columns: [
    		         { text: '用户ID',  dataIndex: 'uid',align: 'center',hidden:true,sortable:false },
    		        { text: '用户名',  dataIndex: 'uname',align: 'center',
    		        	 sortable:false },
    		        { text: '邮箱', dataIndex: 'email',align: 'center',sortable:false },
    		        { text: '电话', dataIndex: 'phone',align: 'center',sortable:false },
    		        { text: '注册IP', dataIndex: 'regIp',align: 'center',sortable:false },
    		        { text: '注册时间', dataIndex: 'regTime',align: 'center',scope:this,renderer:function(value){
    		        	var val=longToString(value,'Y-m-d H:m:s')
    		        	//console.info('获取的值为:{}'+value+' , '+val);
    		        	return  val;
    		        } }
    		    ],
    		  forceFit:true,//强制列表宽度自适应
    		   autoLoad:true,
    		    tbar: Ext.create('Ext.toolbar.Toolbar',{
    		    	
    		    	//width   : 500,
    				items: [{
    					text: '删除',
    					xtype: 'button',
    					iconCls: 'delete',
    					id: 'user_delete',
    					handler: userInfoDel
    				},{
    					text:'添加',
    					xtype:'button',
    					iconCls:'add',
    					id:'user_add',
    					handler:userInfoAdd
    				},{
    					text:'修改',
    					xtype:'button',
    					iconCls:'update',
    					id:'user_update',
    					handler:userInfoUpdate
    				}]
    		    	
    		    }),
    		    renderTo: Ext.getBody(),
    		    //分页
    		    bbar: Ext.create('Ext.toolbar.Paging',{
    		    	beforePageText:'当前第',
    		    	afterPageText:'页',
    		    	refreshText:'刷新',
    		    	store:userStore,
    		    	displayInfo:true,
    		    	displayMsg:'显示:{0}-{1}条,总共:{2}条',
    		    	emptyMsg:'当前查询无记录'
    		    })
    		});
      });
      
    
      
      
      //删除用户信息
      function userInfoDel(){
    
    	  var uid='';
    	  var selectionModel = Ext.getCmp('userGridPanel').getSelectionModel();
    	  var selection = selectionModel.getSelection();
    	  if(selection.length==0){
    		  Ext.Msg.alert("提示","请选择要删除的记录!");
    		  return ;
    	  }else{
                Ext.Msg.confirm("提示","确定删除?",function(button, text){
    				console.info(button+","+text);
    				if(button=="yes"){
    					for(var i=0;i<selection.length;i++){
    						uid = uid+selection[i].get('uid')+",";
    					}
    					Ext.Ajax.request({
    						url: '${pageContext.request.contextPath}/back/user/delete.do',
    						params:{uid:uid},
    						/**
    						 *Object {request: Object, requestId: 3, status: 200, statusText: "OK",
    		   *  responseText: "{"restMsg":"用户删除成功!","success":true}"…}
    						 * @param response
    						 * @param opts
    						 */
    						success: function(response, opts) {
    
    							Ext.Msg.alert("信息提示",response.responseText.restMsg);
    							Ext.getCmp('userGridPanel').getStore().reload();
    						},
    						failure: function(response, opts) {
    							Ext.Msg.alert("信息提示",response.responseText.restMsg);
    						}
    					});
    				}
    			});
    
    	  }
    
    	  
      }
      
      
      
      //修改用户信息
      function userInfoUpdate(){
    	  
    	  var selectionModel = Ext.getCmp('userGridPanel').getSelectionModel();
    	  var selection = selectionModel.getSelection();
    	  if(selection.length==0){
    		  Ext.Msg.alert("提示","请选择要修改的记录!");
    		  return ;
    	  }
    	  
    	  if(selection.length>1){
    		  Ext.Msg.alert("提示","只能修改一条记录!");
    		  return ;
    	  }
    	  //获取选择的记录
    	  var record =selectionModel.getLastSelected();
    	  console.info(record.get("email")+","+record.get("phone"));
    	  
      }
    

     看分页后台实现:

    1.在mybatis配置文件中添加配置:

    <plugins>
            <plugin interceptor="com.github.pagehelper.PageHelper">
                <!-- 4.0.0以后版本可以不设置该参数 -->
                <!--<property name="dialect" value="mysql"/>-->
                <!-- 该参数默认为false -->
                <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
                <!-- 和startPage中的pageNum效果一样-->
                <property name="offsetAsPageNum" value="true"/>
                <!-- 该参数默认为false -->
                <!-- 设置为true时,使用RowBounds分页会进行count查询 -->
                <property name="rowBoundsWithCount" value="true"/>
                <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
                <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
                <property name="pageSizeZero" value="true"/>
                <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
                <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
                <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
                <property name="reasonable" value="true"/>
                <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
                <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
                <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默认值 -->
                <!-- 不理解该含义的前提下,不要随便复制该配置 -->
                <property name="params" value="pageNum=start;pageSize=limit;"/>
                <!-- 支持通过Mapper接口参数来传递分页参数 -->
                <property name="supportMethodsArguments" value="true"/>
                <!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->
                <property name="returnPageInfo" value="check"/>
            </plugin>
        </plugins>

    或者在spring的配置文件中添加配置:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="mapperLocations">
        <array>
          <value>classpath:config/mapper/*.xml</value>
        </array>
      </property>
      <property name="typeAliasesPackage" value="com.test.pojo"/>
      <property name="plugins">
        <array>
          <bean class="com.github.pagehelper.PageHelper">
            <property name="properties">
              <value>
                dialect=mysql
              </value>
            </property>
          </bean>
        </array>
      </property>
    </bean>

    2. dao 文件:

    public interface UserDao extends BaseDao {
        
        List<User> queryForUsers(Map<String, Object> map);
    
        @Override
        int delete(int id) throws Exception;
    
    
    }

    service层对应文件:

    /**
     * @author zhangtb
     * @date 2015年12月20日13:26:50
     */
    
    @Service
    public class UserService {
        
        @Autowired
        private UserDao userDao;
    
        
        public List<User> queryForUsers(Map<String, Object> map){
            return userDao.queryForUsers(map);
        }
    
        
    
    }

    3.controller中分页实现:

    /**
         * 用户列表信息
         */
        @RequestMapping("/userList")
        @ResponseBody
        public void userList(HttpServletRequest request,Writer writer){
            String name = request.getParameter("name");
            Page page = PageUtil.getPage(request);
            Map<String, Object> map = new HashMap<String,Object>();
            map.put("name",name);
            map.put("page",page.getPage());
            map.put("limit",page.getLimit());
            PageHelper.startPage((Integer) map.get("page"),(Integer)map.get("limit"));
            List<User> userList=userService.queryForUsers(map);
            PageInfo<User> pageInfo=new PageInfo<>(userList);
            List<User> users=pageInfo.getList();
            long total = pageInfo.getTotal();
            JSONObject row=new JSONObject();
            JSONArray ary = new JSONArray();
            for(User user :users){
                ary.add(user);
            }
            row.put("rows",ary);
            row.put("total",total);
            try {
                writer.write(row.toJSONString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    返回数据为:

    {"total":12,"rows":[{"email":"233434@163.com","phone":"17890123421","regIp":"127.0.0.1","regTime":1454883085000,"uid":1,"uname":"admin"},{"email":"434234234234","phone":"3242432423","regIp":"127.0.0.1","regTime":1456997965000,"uid":2,"uname":"我看"},{"email":"233434@163.com","phone":"17890123421","regIp":"","regTime":1456394760000,"uid":4,"uname":"Test_001"},{"email":"233434@163.com","phone":"17890123421","regIp":"172.189.12.32","regTime":1456394760000,"uid":5,"uname":"TEST_002"},{"email":"233434@163.com","phone":"18910121322","regIp":"localhost","regTime":1454926128000,"uid":6,"uname":"TEST_003"},{"email":"fsfs@sina.com.cn","phone":"19019324321","regIp":"localhost","regTime":1454969111000,"uid":7,"uname":"Test_0023"},{"email":"fsfs@sina.com.cn","phone":"19019324321","regIp":"localhost","regTime":1454969389000,"uid":8,"uname":"Test_0024"},{"email":"fsfs@sina.com.cn","phone":"19019324321","regIp":"localhost","regTime":1454969390000,"uid":9,"uname":"Test_0025"},{"email":"fsfs@sina.com.cn","phone":"19019324321","regIp":"localhost","regTime":1454969390000,"uid":10,"uname":"Test_0026"},{"email":"fsfs@sina.com.cn","phone":"19019324321","regIp":"localhost","regTime":1454969390000,"uid":11,"uname":"Test_0027"}]}

    至此,mybatis的分页实现结束。

  • 相关阅读:
    phpcms配置404页面
    百度蜘蛛IP地址大全
    36.99.136.*和111.7.100.*两个IP段探究
    讯搜xunsearch的安装与简单使用方法
    wget命令批量下载图片,有规律的url
    wget命令批量下载图片
    宝塔+云锁Nginx自编译web防护亲测教程
    一键下载大学慕课等课程视频
    这些学习网站你一定不可以错过
    第8组 Alpha(1/6)(赵红霞)
  • 原文地址:https://www.cnblogs.com/lonelywolfmoutain/p/5204023.html
Copyright © 2020-2023  润新知