论坛首页 Web前端技术论坛

ext grid 数据库分页实现

浏览 6358 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (3) :: 隐藏帖 (1)
作者 正文
   发表时间:2008-06-10  
     看了robbin 关于hibernate 分页的老帖(http://www.iteye.com/topic/261),把ext grid 的数据库分页整了下,完全满足需要,呵呵,贴出代码与大家共同学习下:
  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{//返回空数据,格式:{"rows":[],"results":"0"}
			List list = new ArrayList();
			Map map1 = new HashMap();
			list.add(map1);
			Map m = new  HashMap();
			m.put("results", "0");
			m.put("rows", list);
			JSONArray json = JSONArray.fromObject(m);		
			String jsonString = json.toString();
			String jsonstr =jsonString.substring(1, jsonString.length()-1);
			response.setContentType("text/json; charset=utf-8"); 
			try {
				response.getWriter().print(jsonstr);
			} catch (IOException e) {
				log.error("获取日志实例列表失败,异常:"+e.getMessage());
			}
		}		
		return null;
	}
 
开始无数据时怎么也不能显示PagingToolbar 的emptyMsg,后来发现空数据时组织格式错误,忘记去掉 [{"rows":[],"results":"0"}]这部分的“[]”,这个小问题折磨了俺好久,呵呵,要细心啊~!
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
             })		
	});

   搞定,收工....
   发表时间:2009-01-23  
开始无数据时怎么也不能显示PagingToolbar 的emptyMsg,后来发现空数据时组织格式错误,忘记去掉 [{"rows":[],"results":"0"}]这部分的“[]”,这个小问题折磨了俺好久,呵呵,要细心啊~!

恩 也折磨了我好久!
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics