前阶段使用了JQuery paganition进行分页,写一个简单的例子与大家分享一下!
实体类User
package com.guchao.pagination.entity;
import java.util.Date;
public class User {
private int id;
private String username;
private int age;
private Date birthday;
public User(){}
public User(int id, String username, int age, Date birthday) {
this.id = id;
this.username = username;
this.age = age;
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
请求的Servlet
package com.guchao.pagination.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import com.guchao.pagination.entity.ResultJSonObject;
import com.guchao.pagination.entity.User;
import com.guchao.pagination.util.JsonDateValueProcessor;
public class TestPaginationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int pageNo = Integer.parseInt(req.getParameter("pageNo"));
int pageSize = Integer.parseInt(req.getParameter("pageSize"));
System.out.println(pageNo+","+pageSize);
int startRow = pageNo * pageSize;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int count = 0;
List data = new LinkedList();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myhibernate", "root", "mysql");
stmt = con.createStatement();
String countSql = "select count(*) from t_user";
rs = stmt.executeQuery(countSql);
if(rs.next()){
count = rs.getInt(1);
}
String sql = "select id,username,age,birthday from t_user limit "+startRow+","+pageSize;
rs = stmt.executeQuery(sql);
while(rs.next()){
User u = new User(rs.getInt("id"),rs.getString("username"),rs.getInt("age"),rs.getDate("birthday"));
data.add(u);
System.out.println(rs.getInt("id")+","+rs.getString("username")+","+rs.getInt("age")+","+rs.getDate("birthday"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally{
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
ResultJSonObject returnObject = new ResultJSonObject();
returnObject.setTotal(count);
returnObject.setResult(data);
//因为返回数据中带有日期类型,必须要使用这个处理类进行处理
JsonConfig config = new JsonConfig();
config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd"));
JSONObject jsonObject = JSONObject.fromObject(returnObject, config);
System.out.println(jsonObject.toString());
resp.getWriter().write(jsonObject.toString());
}
}
返回JSON对象类
package com.guchao.pagination.entity;
import java.util.List;
public class ResultJSonObject {
public int total;
public List<Object> result;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<Object> getResult() {
return result;
}
public void setResult(List<Object> result) {
this.result = result;
}
}
JSON日期类型的处理类
package com.guchao.pagination.util;
import java.text.SimpleDateFormat;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class JsonDateValueProcessor implements JsonValueProcessor {
public static final String Default_DATE_PATTERN = "yyyy-MM-dd";
private SimpleDateFormat dateFormat;
public JsonDateValueProcessor(String datePattern){
try {
dateFormat = new SimpleDateFormat(datePattern);
} catch (Exception e) {
dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);
}
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value);
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
return process(value);
}
private Object process(Object value) {
if (value == null) {
return "";
} else {
return dateFormat.format(value);
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>TestPagination</servlet-name> <servlet-class>com.guchao.pagination.servlet.TestPaginationServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestPagination</servlet-name> <url-pattern>/testPagination.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
JSP页面
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript" src="jquery.pagination.js"></script>
<link rel="styleSheet" type="text/css" href="pagination.css">
<script type="text/javascript">
var items_per_page = 3;//每页显示记录数
var page_index = 0;//起始页
function getDataList(index){
$.ajax({
type:"POST",
url:"testPagination.do",//请求servlet
data:"pageNo="+index+"&pageSize="+items_per_page,//请求参数,页码号和每页显示的记录数
dataType:"json",//返回值类型为JSON
contentType:"application/x-www-form-urlencoded",
success:function(msg){
var total = msg.total;//记录数
var html="<table><tr><th>id</th><th>name</th><th>age</th><th>birthday</th></tr>";
$.each(msg.result,function(i,n){
html+= "<tr><td>"+n.id+"</td><td>"+n.username+"</td><td>"+n.age+"</td><td>"+n.birthday+"</td></tr>";
});
html += "</table>";
$('#Searchresult').html(html);//数据显示
//分页组件显示
if($("#Pagination").html().length == ''){
$("#Pagination").pagination(total, {
'items_per_page' : items_per_page, //每页显示记录数
'num_display_entries' : 10, //可见的页码数
'num_edge_entries' : 2, //显示边缘页码的数目
'prev_text' : "上一页",
'next_text' : "下一页",
'callback' : pageselectCallback
});
}
}
});
}
//page_index 页码号
function pageselectCallback(page_index, jq){
getDataList(page_index);
}
$(document).ready(function(){
getDataList(page_index);
});
</script>
</head>
<body>
<dl id="Searchresult">
<dt>
Search Results will be inserted here ...
</dt>
</dl>
<br style="clear: both;" />
<div id="Pagination" class="pagination"></div>
<br style="clear: both;" />
</body>
</html>
项目结构和页面效果图请看附件图片!