
1、學生列表的 HTML部分
<script type="text/javascript">
$(function(){
//創建dataGrid
$("#dg").datagrid({
url:'StudentServlet', //數據來源
//凍結列
frozenColumns:[[
{field:'id',checkbox:true},
{field:'sno',title:'學號',width:100,sortable:true} ]], \\可排列
//列的定義
columns:[[
{field:'sname',title:'姓名',width:100},
{field:'sclass',title:'班級',width:100,align:'right'},
{field:'ssex',title:'性別',width:100,align:'center',hidden:false},
{field:'sbirthday',title:'生日',width:100,align:'center' }
]],
fitColumns:true, //不能和凍結列同時設置
striped:true,//斑馬線效果
idField:'sno',//主鍵列,
rownumbers:true,//顯示行號
singleSelect:false,//是否單選
pagination:true,//顯示分頁欄
pageList:[5,10,20],//每頁行數選擇列表
pageSize:5,//初始頁面大小
remoteSort:false,//是否服務器端排序
toolbar:[
{iconCls:'icon-edit',text:'跳到第2頁',
handler:function(){$('#dg').datagrid('gotoPage', 2)}
},
{iconCls:'icon-edit',text:'跳到第3頁',
handler:function(){$('#dg').datagrid('gotoPage', 3)}
}
]
});
})
</script>
數據表格<br>
<table id="dg"></table>
</body>
2、StudentServlet部分(數據來源)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html"); \\漢化
String spage = request.getParameter("page"); \\獲取page
String srows = request.getParameter("rows"); \\獲取rows
if(spage!=null&&srows!=null)
{
int page =Integer.parseInt(spage);
int rows =Integer.parseInt(srows);
String json = new StudentService().getPageJSON(page,rows); \\調用方法
response.getWriter().println(json);
}
else
{
response.getWriter().println("{'total':0,'row':[]}" );
}
}

3、StudentService() 類
public class StudentService {
//查詢分頁數據
//返回JSON
public String getPageJSON(int page,int rows)
{
String rtn = "{\"total\":0,\"row\":[]}" ;
int total = new StudentDAO().getTotal();
if(total > 0 )
{
List<Student> ls = new StudentDAO().getPageList(page, rows);
String ls_json = JSONArray.toJSONString(ls);
rtn = "{\"total\":"+total+",\"rows\":"+ls_json+"}"; \\規范 json 格式
}
return rtn;
}
}
4、StudentDAO()類內的 getPageList(獲取分頁數據集合) 和 getTotal(獲取數據條數) 的方法
//獲取分頁數據集合
public List<Student> getPageList(int page, int rows)
{
List<Student> rtn = new ArrayList<Student>();
init();
rtn = se.createQuery("from Student order by sno").
setMaxResults(rows).setFirstResult((page-1)*rows)
.list();
destroy();
return rtn;
}
//獲取數據條數
public int getTotal()
{
int rtn = 0;
init();
List<Object> lo = se.createQuery("select count(1) from Student").list();
if(lo!=null&&lo.size()>0)
{
rtn = Integer.parseInt(lo.get(0).toString());
}
destroy();
return rtn;
}