EXT 3.x 使用详解之Ext.History浏览器前进后退功能(二)--整合grid分页

这篇是针对我以前所写的一个例子进行了对history的修改,修改以后可以针对URL的带参数链接进行访问具体某一页,比如http://localhost:8080/MyTest/ext/test_history_2.jsp#start-6--limit-3直接打开的是第三页,而不是一开始打开就是第一页,再进行扩展以后可以记录例如搜索等关键字。。。当然最基本的也就是增加了浏览器的前进后退功能啦,下面介绍具体代码(自己导入json相关类以及ext相关js):

1.test_history_2.jsp代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page pageEncoding="UTF-8"%>
<html>
<head>

<style type="text/css">
	
	html,body{
	margin:0px;
	height:100%;
	}
	
	#content{
	height:100%;
	width:100%;
	}
</style>

</head>
	<body style="height:100%">
	<script type="text/javascript">
	//本例加入了grid组件的ajax以及分页的功能
	var grid;
	
	var cm;
	
	var ds;
	//分页标签栏
	var bbar;
	//全局高度设定,用来调整整个grid的高度
	var h;
	//设置主截断符
    var maintokenDelimiter = '--';
    //设置次截断符
    var tokenDelimiter = '-';
	//为history保存的params对象
	var o = {};
	//性别详细
	function renderSex(value) {
		if (value == 'male') {
		return "<span style='color:red;font-weight:bold;'>男</span>";
		} else {
		return "<span style='color:green;font-weight:bold;'>女</span>";
		}
	}
	//描述详细
	function renderDescn(value, cellmeta, record, rowIndex, columnIndex,store){
		var str = (rowIndex+1)+"行|"+(columnIndex+1)+"列";
		return str;
	}
	
	Ext.onReady(function()
		{
	//初始化history组件
 	Ext.History.init();
 
	//对列的定义
	cm = new Ext.grid.ColumnModel([
		{header:'<font color="blue">编号</font>',width: Ext.get("content").getWidth()/5,sortable:true,dataIndex:'id'},//sortable 可排序,具体体现在有排序选项卡
		{header:'<font color="blue">日期</font>',width: Ext.get("content").getWidth()/5,dataIndex:'time',renderer:Ext.util.Format.dateRenderer('Y-m-d h:i:s')},
		{header:'<font color="blue">性别</font>',width: Ext.get("content").getWidth()/5,dataIndex:'sex',renderer:renderSex},
		{header:'<font color="blue">名称</font>',width: Ext.get("content").getWidth()/5,dataIndex:'name'},
		{header:'<font color="blue">描述</font>',width: Ext.get("content").getWidth()/5,dataIndex:'descn',renderer:renderDescn}
	]);
	//ajax代理
	var proxyParam={  
        url:contextPath + '/search.do?method=SearchAjax',  
        method:'GET'  
   	 }; 
	//对ajax返回的json数据进行解析,
	var jsonReaderMeta={  
		root: 'grids',//Json对象的root名称,与SearchVO的属性相对应
		totalProperty: 'totalCount', //数据的总行数 ,与SearchVO的属性相对应
   		id: 'id'  //数据的主键,与GridVO的属性相对应
     };  
	//解析Json数据的类型
	var recordType=[  
        {name: 'id', mapping: 'id'}, 
        //日期类型如果是String也可以表明为date型,不过需要标明pattern,具体pattern可查api中date类
        {name: 'time', mapping: 'time',type : 'date',dateFormat : 'Y-m-d h:i:s' },   
        {name: 'sex', mapping: 'sex'},  
        {name: 'name', mapping: 'name'},  
        {name: 'desc', mapping: 'desc'}  
      ]; 
	//定义dataStore
	ds = new Ext.data.Store({  
        proxy: new Ext.data.HttpProxy(proxyParam),  
        reader: new Ext.data.JsonReader(jsonReaderMeta,recordType),
        remoteSort:true  //允许到后台进行排序
     });
     //定义分页标签
	bbar = new Ext.PagingToolbar({
		pageSize: 3,
		store: ds,
		displayInfo: true,
		displayMsg: '第{0} 到 {1} 条数据 共{2}条',
		emptyMsg: "没有数据",
		//获得start参数以便加入history等方法
		doLoad: function(start){
			/***源码中执行类似此段内容
	            var o = {};
	            var pn = this.store.paramNames;  
	         o[pn.start] = start;  
				o[pn.limit] = this.pageSize;  
				this.store.load({params:o});  
			***/	
			
	        var pn = this.store.paramNames;  
			//改为history操作
			Ext.History.add(pn.start+tokenDelimiter+start+maintokenDelimiter+pn.limit+tokenDelimiter+this.pageSize);
		}  
      }); 
	//创建grid对象
	grid = new Ext.grid.GridPanel({
		renderTo: 'content',
		width: Ext.get("content").getWidth(),
		store: ds,
		cm: cm,
		loadMask: true,
		bbar: bbar
		//如果需要每列自动填满Grid,可以使用viewConfig配置中的foreceFit
		//viewConfig:{forceFit:true}
	});
	//加载dataStore,此时可以带一些必要的参数提交到后台
        //此处交由history来触发ds.load就不用自己加载了,已经注释掉
	//ds.load({params:{start:0, limit:3}});
	//在dataStore加载的时候进行高度的自动调整
	ds.on('load', function(){ 
		h = $('.x-panel-bbar').height()+$('.x-grid3-body').height()+$('.x-grid3-header').height()+20;
		grid.setHeight(h); 
       });
    
     //获取浏览器hash中#后面的字符串
    Ext.History.on('change', function(token){
        if(token){
        //如果有字符串则进行相应处理
        	var parts = token.split(maintokenDelimiter);
        	for(i=0;i<parts.length;i++){
       			if(!Ext.isEmpty(parts[i])){
        			var keyword = parts[i].split(tokenDelimiter);
        			o[keyword[0]] = parseInt(keyword[1]);  
       			}
        	}
        	bbar.store.load({params:o});
        }
    });
    
    //如果使用带有参数的url直接访问,那么由loadHref()方法进行解释
    function loadHref(){
    	var href = window.location.href;
    	if(href.indexOf('#')>0){
    	  var o = href.split('#');
    	  //激活history的change事件
		  Ext.History.fireEvent('change',o[1]);     	
    	}else{
    	  //直接默认第一个标签页, 激活history的change事件
    	  Ext.History.add("start-0--limit-"+bbar.pageSize);
    	  Ext.History.fireEvent('change',"start-0--limit-"+bbar.pageSize);     
    	}
    }
	loadHref();
    
	});
	
	
	//自动适应浏览器窗口调整
	window.οnresize=function(){
		cm = new Ext.grid.ColumnModel([
			{header:'<font color="blue">编号</font>',width: Ext.get("content").getWidth()/5,sortable:true,dataIndex:'id'},
			{header:'<font color="blue">日期</font>',width: Ext.get("content").getWidth()/5,dataIndex:'time',renderer:Ext.util.Format.dateRenderer('Y年m月d日h时m分s秒')},
			{header:'<font color="blue">性别</font>',width: Ext.get("content").getWidth()/5,dataIndex:'sex',renderer:renderSex},
			{header:'<font color="blue">名称</font>',width: Ext.get("content").getWidth()/5,dataIndex:'name'},
			{header:'<font color="blue">描述</font>',width: Ext.get("content").getWidth()/5,dataIndex:'descn',renderer:renderDescn}
		]);
		if(grid){
			grid.setWidth(Ext.get("content").getWidth());
			//重新载入dataStore和cm,此时会根据数据以及新设定的cm自动调整宽和高
	        grid.reconfigure(ds,cm);
        }
	};
	
    </script>
    
<div id="content"><div>
	<!-- Ext.History所需的form  begin-->
		<form id="history-form" class="x-hidden">  
             <input type="hidden" id="x-history-field" />  
             	<iframe id="x-history-frame">  
             </iframe>  
        </form> 
    <!-- Ext.History所需的form  end -->  
	</body>
</html>

 

 


2.下面是后台search.do部分(注意实用了json数据类型,请加入json相关的包):

 

public ActionForward SearchAjax(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Integer start = Integer.valueOf(request.getParameter("start"));
		Integer limit = Integer.valueOf(request.getParameter("limit"));
		System.out.println("start:" + start + "|limit:" + limit);
		String sort = request.getParameter("sort");
		String dir = request.getParameter("dir");
		if (StringUtils.isBlank(sort)) {
			sort = "id";
		}
		if (StringUtils.isBlank(dir)) {
			dir = "ASC";
		}
		System.out.println("sort:" + sort + "|" + dir);
		List<GridVO> lists = new ArrayList<GridVO>();
		GridVO vo = new GridVO();
		vo.setId(1);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name1");
		vo.setDesc("descn1");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(2);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name2");
		vo.setDesc("descn2");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(3);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name3");
		vo.setDesc("descn3");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(4);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name4");
		vo.setDesc("descn4");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(5);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name5");
		vo.setDesc("descn5");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(6);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name6");
		vo.setDesc("descn6");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(7);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name7");
		vo.setDesc("descn7");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(8);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name8");
		vo.setDesc("descn8");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(9);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name9");
		vo.setDesc("descn9");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(10);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name10");
		vo.setDesc("descn10");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(11);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name11");
		vo.setDesc("descn11");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(12);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name12");
		vo.setDesc("descn12");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(13);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name13");
		vo.setDesc("descn13");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(14);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name14");
		vo.setDesc("descn14");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(15);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name15");
		vo.setDesc("descn15");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(16);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name16");
		vo.setDesc("descn16");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(17);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name17");
		vo.setDesc("descn17");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(18);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name18");
		vo.setDesc("descn18");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(19);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name19");
		vo.setDesc("descn19");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(20);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name20");
		vo.setDesc("descn20");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(21);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name21");
		vo.setDesc("descn21");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(22);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name22");
		vo.setDesc("descn22");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(23);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name23");
		vo.setDesc("descn23");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(24);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name24");
		vo.setDesc("descn24");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(25);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name25");
		vo.setDesc("descn25");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(26);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name26");
		vo.setDesc("descn26");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(27);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name27");
		vo.setDesc("descn27");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(28);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name28");
		vo.setDesc("descn28");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(29);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name29");
		vo.setDesc("descn29");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(30);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name30");
		vo.setDesc("descn30");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(31);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name31");
		vo.setDesc("descn31");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(32);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name32");
		vo.setDesc("descn32");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(33);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name33");
		vo.setDesc("descn33");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(34);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name34");
		vo.setDesc("descn34");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(35);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name35");
		vo.setDesc("descn35");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(36);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name36");
		vo.setDesc("descn36");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(37);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name37");
		vo.setDesc("descn37");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(38);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name38");
		vo.setDesc("descn38");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(39);
		vo.setTime(dateFormat());
		vo.setSex("male");
		vo.setName("name39");
		vo.setDesc("descn39");
		lists.add(vo);
		vo = new GridVO();
		vo.setId(40);
		vo.setTime(dateFormat());
		vo.setSex("female");
		vo.setName("name40");
		vo.setDesc("descn40");
		lists.add(vo);
		// 排序
		lists = sortObj(lists, sort, dir);

		SearchVO searchVO = new SearchVO();
		searchVO.setTotalCount(lists.size());
		lists = findCurrentPageObj(lists, start, limit);
		searchVO.setGrids(lists);
		JSONObject obj = JSONObject.fromObject(searchVO);
		System.out.println(obj.toString());
		response.setContentType("text/xml;charset=utf-8");
		response.getWriter().print(obj.toString());
		return null;
	}

	private List<GridVO> sortObj(List<GridVO> list, String sort, String dir) {
		Set<ResultTokenDelegate> someSet = new TreeSet<ResultTokenDelegate>();
		List<GridVO> result = new ArrayList<GridVO>();
		for (GridVO res : list) {
			ResultTokenDelegate delegate = new ResultTokenDelegate(res, sort,
					dir);
			someSet.add(delegate);
		}
		Iterator iterator = someSet.iterator();
		while (iterator.hasNext()) {
			ResultTokenDelegate delegate = (ResultTokenDelegate) iterator
					.next();
			result.add(delegate.getResult());
		}
		return result;
	}

	List<GridVO> findCurrentPageObj(List<GridVO> list, int start, int limit) {
		List<GridVO> vos = new ArrayList<GridVO>();
		for (int i = 0; i < list.size(); i++) {
			if (i >= start && i < (start + limit)) {
				vos.add(list.get(i));
			}
		}
		return vos;
	}

	String dateFormat() {
		SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date = new Date(System.currentTimeMillis());
		return smf.format(date);
	}

 


3.ResultTokenDelegate类的代码,用来为list对象排序的:

package com.xuyi.util.sort;

import com.xuyi.vo.GridVO;

public class ResultTokenDelegate implements Comparable {

	private GridVO result;

	private String sort;

	private String dir;

	public ResultTokenDelegate() {
	}

	public ResultTokenDelegate(GridVO result, String sort, String dir) {
		this.result = result;
		this.sort=sort;
		this.dir=dir;
	}

	public GridVO getResult() {
		return result;
	}

	public void setResult(GridVO result) {
		this.result = result;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int compareTo(Object o) {
		ResultTokenDelegate ntd = (ResultTokenDelegate) o;
		if ("id".equals("id")) {
			if ("ASC".equals(dir)) {
				if (this.getResult().getId() < ntd.getResult().getId()) {
					return -1;
				} else if (this.getResult().getId() == ntd.getResult().getId()) {
					return 1;
				} else {
					return 1;
				}
			}else{
				if (this.getResult().getId() < ntd.getResult().getId()) {
					return 1;
				} else if (this.getResult().getId() == ntd.getResult().getId()) {
					return 1;
				} else {
					return -1;
				}
			}
		}else{
			return 1;
		}
	}

}

 

4.GridVO类的代码:

package com.xuyi.vo;

public class GridVO {
	
	int id;
	
	String sex;
	
	String name;
	
	String desc;
	
	String time;


	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
	
	
}

5. SearchVO的代码:

package com.xuyi.vo;

import java.util.ArrayList;
import java.util.List;

public class SearchVO {
	
	int totalCount;
	
	List<GridVO> grids = new ArrayList<GridVO>();

	public List<GridVO> getGrids() {
		return grids;
	}

	public void setGrids(List<GridVO> grids) {
		this.grids = grids;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	
	
}

 

6.具体效果可以通过直接访问例如:http://localhost:8080/MyTest/ext/test_history_2.jsp#start-6--limit-3

这样的URL就可以直接页面grid显示第3页的内容了,当然还能前进后退咯,呵呵

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值