ext grid 数据库分页实现

public ActionForward getAllLogs(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		String startResult = request.getParameter("start");
		String limitResult = request.getParameter("limit");
		String sortRecord = request.getParameter("sort");
		String dirRecord = request.getParameter("dir");
		
		JSONArray jsonArray = this.getLogService().getAllLogs(startResult,limitResult,sortRecord,dirRecord);		
		
		if(jsonArray != null){
			String jsonstr = jsonArray.toString();
			//去除JSON对象前的[]  
			String json = jsonstr.substring(1, jsonstr.length()-1);			
			response.setContentType("text/json; charset=utf-8"); 
			try {
				response.getWriter().print(json);
			} catch (IOException e) {
				log.error("获取日志实例列表失败,异常:"+e.getMessage());
			}
		}else	
		return null;
	}

看了robbin 关于hibernate 分页的老帖(http://www.javaeye.com/topic/261),把ext grid 的数据库分页整了下,功能是实现了,到是也有个ext的小问题,就是无数据时ext grid分页栏的emptyMsg无法显示,现帖出所有代码,与大家共同探讨下:
  DAO代码:

/**
	   * 获取符合查询条件的记录总数
	   * @param detachedCriteria  hibernate Criteria 查询对象,由service组装
	   * @return
	   */
  public Long getRecordCount(final DetachedCriteria detachedCriteria) {
		return (Long) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Criteria criteria = detachedCriteria
						.getExecutableCriteria(session);
				long count = Long.parseLong((criteria.setProjection(Projections
						.rowCount()).uniqueResult()).toString());
				criteria.setProjection(null);
				return Long.valueOf("" + count);
			}
		}, true);
	}
/**
	   * 获取符合条件的查询记录
	   * @param detachedCriteria
	   * @param startResult
	   * @param limitResult
	   * @return
	   */

	public List listByConditions(final DetachedCriteria detachedCriteria,
			final int startResult, final int limitResult) {

		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Criteria criteria = detachedCriteria
						.getExecutableCriteria(session);
				criteria.setFirstResult(startResult);
				criteria.setMaxResults(limitResult);
				return criteria.list();
			}
		}, true);
	} 
  

 服务层:

/**
	 * 获取所有日志列表
     * @param startResult   查询记录起点
     * @param limitResult   简要列表每页最大记录数
     * @param sortRecord    简要列表排序字段名
     * @param dirRecord     简要列表排序类型 DESE/ASC
	 * @return
	 */
public JSONArray getAllLogs(String startResult,String limitResult,
			  String sortRecord,String dirRecord) {
		
		try {
			DetachedCriteria detachedCriteria = DetachedCriteria.forClass(TDeasLog.class);  
			if(dirRecord.equals("ASC"))
				detachedCriteria.addOrder(Order.asc(sortRecord));
			else
				detachedCriteria.addOrder(Order.desc(sortRecord));
			  
			Long count = logDAO.getRecordCount(detachedCriteria);//获取符合条件的记录总数	  
			  
			List list = logDAO.listByConditions(detachedCriteria, Integer.parseInt(startResult), 
					  Integer.parseInt(limitResult));//获取符合条件记录
			if(list.size()>0){
				List jsonlist = new ArrayList();
				Iterator it = list.iterator();
				while (it.hasNext()){
					Log log = (Log )it.next();
					Map map = new HashMap();
					map.put("taskId", log .getTaskId());
					map.put("rwfssj", log .getRwfssj());
					map.put("rwjssj", log .getRwjssj());
							....													
					jsonlist.add(map);				
				}
				Map m = new  HashMap();
				m.put("results", count.toString());
				m.put("rows", jsonlist);
				
				JSONArray jsonArray = JSONArray.fromObject(m);
				return jsonArray;  
			}else
				return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
action 代码:
public ActionForward getAllLogs(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		String startResult = request.getParameter("start");
		String limitResult = request.getParameter("limit");
		String sortRecord = request.getParameter("sort");
		String dirRecord = request.getParameter("dir");
		
		JSONArray jsonArray = this.getLogService().getAllLogs(startResult,limitResult,sortRecord,dirRecord);		
		
		if(jsonArray != null){
			String jsonstr = jsonArray.toString();
			//去除JSON对象前的[]  
			String json = jsonstr.substring(1, jsonstr.length()-1);			
			response.setContentType("text/json; charset=utf-8"); 
			try {
				response.getWriter().print(json);
			} catch (IOException e) {
				log.error("获取日志实例列表失败,异常:"+e.getMessage());
			}
		}else	
		return null;
	}
看了EXT API,JsonReader处理的数据类型是下面这样:{ 'results': 2, 'rows': [
    { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
    { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
},而我在service层封装后的JSON数据类型却是这样的:[{ 'results': 2, 'rows': [
    { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
    ...
}]也就是说会多一个[],只好在action中把[]去掉,不知道这是不是影响PagingToolbar的emptyMsg无法显示的原因。
JS代码:
 var datastore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'logManage.do?method=getAllLogs'
        }),
        reader: new Ext.data.JsonReader({
        	root               : 'rows',
            totalProperty      : 'results',
            id: 'taskID'
        }, [
            {name: 'taskId'},
            {name: 'rwfssj'},
            {name: 'rwjssj'},
            ....
        ]),
         remoteSort: true
    });
    datastore.setDefaultSort('taskId','ASC');
    datastore.load({params:{start:0, limit:10}});
		
	var sm = new Ext.grid.CheckboxSelectionModel();
	var colModel = new Ext.grid.ColumnModel([
		new Ext.grid.RowNumberer(),
		{ header:'任务ID', width:100, sortable:true, locked:true, dataIndex:'taskId'},
		{ header:'任务类型', width:100, sortable:true, locked:false, dataIndex:'rwlb'},
		{ header:'任务状态', width:100, sortable:true, locked:false, dataIndex:'rwzt'},
		......
	]);
		
	var LogGrid = new Ext.grid.GridPanel({
		ds					: datastore,
		cm					: colModel,
		sm					: sm,
		id                  : 'LogGrid',
		title				: '日志列表',
		autoHeight 		    : true,
        width               : '100%',
        loadMask            : true,
		 buttons            : [{
		        text	    : '查询',
				tooltip	    : '日志查询',
				handler   	: logSearch
		 },{
		        text	    : '关闭',
				tooltip	    : '关闭窗口',
				handler	    : closeForm
		 }],
        buttonAlign         : 'right',
        bbar                : new Ext.PagingToolbar({
            id              : 'pagingbar',
            pageSize        : 10,
            store           : datastore,
            displayInfo     : true,
            displayMsg      : '显示数据记录: {0} - {1} of {2}',
///就是这句怎么整夜显示不了,有米人来瞅瞅看                           
            emptyMsg        : '没有数据记录...' })		
	});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值