ajax 分页 步骤和代码
1.pageUtil工具类
2.DAO两个方法,获得总记录数getPageCounts(),获得分页LIST,findByPage(PageUtil util)
3.Servlet 调用这两个方法得到分页的list,把list整体转换成json格式的数据 传递给前台
4.前台jsp页面,设置page分页区域
5.jquery页面加载中初始化分页js方法。
$(function(){
function pageInit(pageIndex){
$.ajax({ .....
success:callback
})
function callback(data){ 以json等格式包装的(data)以json格式包装的data,遍历信息,
清空上次信息
遍历data
拼接本次信息(这个list(拼接到需要ajax异步的地方。)
}
}
页面js点击$("#one/back/next/").click(function(){ }
})
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
代码=====================================daoImpl
package cn.bdqn.dao;
import java.sql.SQLException;
import java.util.List;
import cn.bdqn.bean.News_Detail;
import cn.bdqn.util.BaseDao;
import cn.bdqn.util.PageUtil;
import cn.bdqn.util.ResultSetUtil;
public class NewsDaoImpl extends BaseDao implements NewsDao {
@Override
public int getPageCounts() {
String sql = "select count(1) from news_detail";
rs = executeQuery(sql);
int rowNum = 0;
try {
if (rs.next()) {
rowNum = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnection();
}
return rowNum;
}
@Override
public List<News_Detail> findNewsByPage(PageUtil util) {
String sql = "select * from news_detail limit ?,? ";
Object[] params = { (util.getPageIndex() - 1) * util.getPageSize(),
util.getPageSize() };
rs = executeQuery(sql, params);
return ResultSetUtil.eachResultSet(rs, News_Detail.class);
}
}
============================================servlet
package cn.bdqn;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.bdqn.bean.News_Detail;
import cn.bdqn.dao.NewsDao;
import cn.bdqn.dao.NewsDaoImpl;
import cn.bdqn.util.PageUtil;
import com.google.gson.Gson;
@WebServlet("/ListServlet")
public class ListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 调用service层的代码 我们没写 直接调用dao
NewsDao dao = new NewsDaoImpl();
PageUtil util = new PageUtil();
// 获取数据库的总记录数
util.setTotalCount(dao.getPageCounts());
// 获取前台传递的参数
String num = req.getParameter("pageIndex");
if (num != null && num != "") {
util.setPageIndex(Integer.parseInt(num));
} else {
util.setPageIndex(1);
}
System.out.println("==================>" + num);
// 调用后台代码 获取 list集合
List<News_Detail> list = dao.findNewsByPage(util);
if (list != null) {
list.get(0).setPageUtil(util); // 给分页的属性赋值
// 需要把list整体转换成json格式的数据 传递给前台
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
resp.setHeader("content-type", "text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.print(json);
writer.close();
}
}
}
====================================================jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<table>
<thead>
<tr>
<th>新闻标题</th>
<th>新闻作者</th>
<th>新闻摘要</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<input type="hidden" name="pageIndex">
<a href="" id="one">首页</a>
<a href="" id="back">上一页</a>
<a href="" id="next">下一页</a>
<a href="" id="last">尾页</a>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){
//分页的四要素
var pageIndex=""; //当前页
var pageSize="";//页大小
var totalPageCount=""; //总页数
var totalCountSize=""; //总记录数
//用户第一次打开这个inde.jsp页面什么数据都没有! 但是必须得有!!!访问后代数据库
pageInit(pageIndex); // 初始化数据
function pageInit(pageIndex){
$("#one").show();
$("#back").show();
$("#next").show();
$("#last").show(); //第一次显示 所有的 超链接
//使用ajax访问servlet
$.ajax({
url:"ListServlet",
type:"POST",
data:{"pageIndex":pageIndex}, //把用户传递的当前页 发送给后台servlet
dataType:"json",
contentType:"application/x-www-form-urlencoded;charset=utf-8",
success:callback //调用回调函数
});
//data 就是 后台传递过来的数据
//每次都需要清空上次的内容
$("#tbody").html("");
$(data).each(function(){ // each start回调函数
if (this.pageUtil!=null) { //给分页四要素赋值
pageIndex=this.pageUtil.pageIndex;
pageSize=this.pageUtil.pageSize;
totalPageCount=this.pageUtil.pageCount;
totalCountSize=this.pageUtil.totalCount;
}
/*开始给tbody拼接
使用快捷键 shift+alt +a 给每一行增加 " +
ctrl+f 替换所有的{ }
*/
$("#tbody").append(
" <tr><td>"+this.title+"</td> "
+" <td>"+this.author+"</td> "
+" <td>"+this.summary+"</td> </tr> ");
});
} // each end
})// callback end
$("#one").click(function(){ //首页
pageInit(1);
});
$("#last").click(function(){ //尾页
pageInit(totalPageCount);
});
$("#back").click(function(){ //上一页
if((pageIndex-1)>0){
pageInit(pageIndex-1);
}else{
$("#one").hide();
$("#back").hide();
}
});
$("#next").click(function(){ //下一页
if((pageIndex+1)<=totalPageCount){
pageInit(pageIndex+1);
}else{
$("#last").hide();
$("#next").hide();
}
});
</script>
</body>
</html>
===========================================pageUtil
package cn.bdqn.util;
/**
* 分页的工具类
*/
public class PageUtil {
private int totalCount;// 总记录数 通过sql从数据库中获取
private int pageSize = 3;// 页大小 每页显示的条数
private int pageCount;// 总页数
private int pageIndex;// 当前页
public int getTotalCount() {
return totalCount;
}
/**
* 我们在获取总记录数之后,肯定可以得出 总页数
* 001.总记录数通过sql从数据库中获取
* 002.三元表达式 进行判断 并赋值总页数pageCount
*
* 总页数=(总记录数%页大小==0)?(总记录数/页大小):(总记录数/页大小+1);
*
* @param totalCount
* 总记录数
*/
public void setTotalCount(int totalCount) {
if (totalCount > 0) {
this.totalCount = totalCount;
this.pageCount = (totalCount % pageSize == 0) ? (totalCount / pageSize)
: (totalCount / pageSize + 1);// 总页数
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public PageUtil(int totalCount, int pageSize, int pageCount, int pageIndex) {
super();
this.totalCount = totalCount;
this.pageSize = pageSize;
this.pageCount = pageCount;
this.pageIndex = pageIndex;
}
public PageUtil() {
super();
}
@Override
public String toString() {
return "PageUtil [totalCount=" + totalCount + ", pageSize=" + pageSize
+ ", pageCount=" + pageCount + ", pageIndex=" + pageIndex + "]";
}
}
===============================================================rs的set,get方法
package cn.bdqn.util;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 01.从数据库获取ResultSet
* 问题? 运行期间 我们知道ResultSet中是什么类型吗?
* 02.从ResultSet结果集中 获取T类型
* 03.根据T类型,向每个属性 赋值
* 04.放进list集合 返回即可
*/
public class ResultSetUtil {
/**
*
* @param rs
* 从数据库获取的数据结果集
* @param clazz
* T类型
* @return T类型的集合
*/
public static <T> List<T> eachResultSet(ResultSet rs, Class<T> clazz) {
List<T> list = new ArrayList<>();
// 循环ResultSet 01.先获取对象 02.循环属性赋值 03.放进集合
try {
T object = null;
while (rs.next()) {
object = clazz.newInstance(); // 实例化对象
Field[] field = clazz.getDeclaredFields(); // 获取实体类的所有属性,返回Field数组
for (Field f : field) {
f.setAccessible(true); // 可以访问私有属性 并赋值
if (f.getName().equals("pageUtil")) {
continue;
}
f.set(object, rs.getObject(f.getName()));
}
list.add(object); // 放进集合
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return list;
}
/**
*
* @param rs
* 从数据库获取的数据结果集
* @param clazz
* T类型
* @return T类型
*/
public static <T> T findT(ResultSet rs, Class<T> clazz) {
T object = null;
try {
if (rs.next()) {
object = clazz.newInstance(); // 实例化对象
Field[] field = clazz.getDeclaredFields(); // 获取实体类的所有属性,返回Field数组
for (Field f : field) {
f.setAccessible(true); // 可以访问私有属性 并赋值
f.set(object, rs.getObject(f.getName()));
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return object;
}
}