JAVAWEB简单模仿百度分页

public class BaseBean {
 private Integer page = 1;
 public Integer getPage(){
    return page; 
 }

}
import java.util.List;

public class QueryResult<T> {

    private List<T> list;
    private long totalRecord;
    public List<T> getList() {
        return list;
    }
    public void setList(List<T> list) {
        this.list = list;
    }
    public long getTotalRecord() {
        return totalRecord;
    }
    public void setTotalRecord(Long totalRecord) {
        this.totalRecord = totalRecord;
    }


}
public class BaseBean {
 private Integer page = 1;
 public Integer getPage(){
    return page; 
 }

}
public class User extends BaseBean {
    private Integer id;
    private String userName;
    private Integer age;

    public User(Integer id,String userName, Integer age) {
        super();
        this.id=id;
        this.userName = userName;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.xukaiqiang.bean.QueryResult;
import com.xukaiqiang.bean.User;
import com.xukaiqiang.util.DBHelper;


public class UserDao {


     */ @Description:分页查询数据库中的数据
     *firstIndex分页的首个参数,表示从第几条记录开始索引
      *pageNum分页的第二个参数,表示索引几条
     */
    public QueryResult<User> queryUser(int firstIndex, int pageNum) {
        QueryResult<User> users = new QueryResult<>();
        List<User> users2 = new ArrayList<>();
        Connection connection = null;
        try {
            // 获取数据库连接
            connection = DBHelper.getConn();
            // SQL语句
            StringBuffer sql = new StringBuffer("select * from t_user");
            sql.append(" limit " + firstIndex + "," + pageNum);
            // 执行SQL语句
            PreparedStatement preparedStatement = connection.prepareStatement(sql.toString());
            ResultSet resultSet = preparedStatement.executeQuery();
            // 获取集合
            while (resultSet.next()) {
                User user = new User(resultSet.getInt("id"),resultSet.getString("userName"), resultSet.getInt("age"));
                users2.add(user);
            }
            users.setList(users2);
            users.setTotalRecord(queryCount());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeConn(connection);
        }
        return users;
    }


    public long queryCount() {
        long totalCount = 0;
        Connection connection = null;
        try {
            // 获取数据库连接
            connection = DBHelper.getConn();
            // SQL语句
            StringBuffer sql = new StringBuffer("select count(*) num from t_user");
            // 执行SQL语句
            PreparedStatement preparedStatement = connection.prepareStatement(sql.toString());
            ResultSet resultSet = preparedStatement.executeQuery();
            // 获取集合
            if (resultSet.next()) {
                totalCount = resultSet.getLong("num");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalCount;
    }
}
import java.util.List;

import com.xukaiqiang.util.Globals;
public class PageView<T> {
    // 总共的页数
    private long totalPage;
    // 当前的页数
    private Integer currentPage;
    // 每页的条数
    private long pageNum = Globals.PAGE_NUM;
    // 总共的记录数
    private long totalRecord;
    // 结果集合
    private List<T> list;
    // 分页信息
    private String pageHtml;
    // 带参构造
    public PageView(Integer currentPage, long totalRecord, List<T> list) {
        super();
        this.currentPage = currentPage;
        this.totalRecord = totalRecord;
        this.list = list;

        // 设置总页数
        setTotalPage(this.totalRecord % this.pageNum == 0 ? this.totalRecord / this.pageNum
                : this.totalRecord / this.pageNum + 1);

        // 设置分页的HTML
        StringBuffer pageHtml = new StringBuffer();
        pageHtml.append("共有" + this.totalRecord + "条记录/第" + this.currentPage + "页/共" + this.totalPage + "页");
        if (this.currentPage > 1) {
            pageHtml.append("<a href='javascript:query(1)'>首页</a>");
        }
        if (this.currentPage > 1) {
            pageHtml.append("<a href='javascript:query(" + (this.currentPage - 1) + ")'>上一页</a>");
        }
        if (this.currentPage < this.totalPage) {
            pageHtml.append("<a href='javascript:query(" + (this.currentPage + 1) + ")'>下一页</a>");
            pageHtml.append("<a href='javascript:query(" + this.totalPage + ")'>末页</a>");
        }
        setPageHtml(pageHtml.toString());
    }

    public String getPageHtml() {
        return pageHtml;
    }

    public void setPageHtml(String pageHtml) {
        this.pageHtml = pageHtml;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public long getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(long totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public long getPageNum() {
        return pageNum;
    }

    public void setPageNum(long pageNum) {
        this.pageNum = pageNum;
    }

    public long getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(long totalRecord) {
        this.totalRecord = totalRecord;
    }


}
import java.util.List;

import com.xukaiqiang.util.Globals;

public class PageViewBaidu<T{
    // 总共的页数
    private int totalPage;
    private int nowPage;// 当前页
    private int startPage;// 起始页
    private int endPage;// 结束页
    private int totalRecord;// 总记录数
    // 分页2
    private String pageHtml2;
    // 结果集合
    private List<T> list;
    public static final int PAGESIZE = Globals.PAGE_NUM;// 每页显示的条数
    public static final int SHOWPAGES = Globals.SHOWPAGES;// 每页显示的页数
    // 带参构造

    public PageViewBaidu(Integer nowPage, int totalRecord, List<T> list) {
        super();
        this.nowPage = nowPage;
        this.totalRecord = totalRecord;
        this.list = list;
        // 设置总页数
        setTotalPage(this.totalRecord % PAGESIZE == 0 ? this.totalRecord / PAGESIZE : this.totalRecord / PAGESIZE + 1);
        /**
         * 计算startPage与endPage的值
         * 
         */

        if (this.totalPage < SHOWPAGES) {
            /** if中是总页数小于SHOWPAGES的情况 */
            this.startPage = 1;
            this.endPage = totalPage;
        } else {
            /** else中是总页数大于SHOWPAGES的情况 */
            if (this.nowPage <= SHOWPAGES / 2 + 1) {
                this.startPage = 1;
                this.endPage = SHOWPAGES;
            } else {
                this.startPage = this.nowPage - (SHOWPAGES / 2);
                this.endPage = this.nowPage + (SHOWPAGES / 2 - 1);
                if (this.endPage >= this.totalPage) {
                    this.endPage = this.totalPage;
                    this.startPage = this.totalPage - SHOWPAGES + 1;
                }
            }
        }

        // 设置分页的HTML
        StringBuffer pageHtml = new StringBuffer();
//        if (this.nowPage > 1) {
//            pageHtml.append("<a href='javascript:query(" + (this.nowPage - 1) + ")'>&lt;上一页</a>");
//        }
//        for (int i = this.startPage; i <= this.endPage; i++) {
//            if (i != this.nowPage) {
//                pageHtml.append("<a href='javascript:query(" + i + ")'>" + i + " </a>");
//            }else{
//                pageHtml.append("[" + i + " ]");
//            }
//        }
//        if (this.nowPage != this.totalPage) {
//            pageHtml.append("<a href='javascript:query(" + (this.nowPage + 1) + ")'>下一页&gt;</a>");
//        }

        pageHtml.append("<nav><ul class='pagination pagination-lg'>");
        if (this.nowPage > 1) {
        pageHtml.append("<li><a href='javascript:query(" + (this.nowPage - 1) + ")' aria-label='上一页'><span aria-hidden='true'>&lt;上一页</span></a>");
        }

        for (int i = this.startPage; i <= this.endPage; i++) {
            if (i != this.nowPage) {
                pageHtml.append("<li><a href='javascript:query(" + i + ")'>" + i + " </a></li>");
            }else{
                pageHtml.append("<li class='active'><a href='javascript:query(" + i + ")'>" + i + " </a></li>");
            }
        }

        if (this.nowPage != this.totalPage) {
            pageHtml.append("<li><a href='javascript:query(" + (this.nowPage + 1) + ")' aria-label='下一页'><span aria-hidden='true'>下一页&gt;</span></a></li>");
        }
        pageHtml.append("</ul></nav>");
        setPageHtml2(pageHtml.toString());
    }

    /**
     * 分页方法 通过这个方法,得到两个数据——startPage和endPage 页面上的页码就是根据这两个数据处理后显示
     * 
     * @param nowPage当前页
     * @param totalPage总页数
     */

    public void paginationTool(int nowPage, int totalPage) {
        this.nowPage = nowPage;
        this.totalPage = totalPage;
        /**
         * 计算startPage与endPage的值
         * 
         */

        if (this.totalPage < SHOWPAGES) {
            /** if中是总页数小于SHOWPAGES的情况 */
            this.startPage = 1;
            this.endPage = totalPage;
        } else {
            /** else中是总页数大于SHOWPAGES的情况 */
            if (this.nowPage <= SHOWPAGES / 2 + 1) {
                this.startPage = 1;
                this.endPage = SHOWPAGES;
            } else {
                this.startPage = this.nowPage - (SHOWPAGES / 2);
                this.endPage = this.nowPage + (SHOWPAGES / 2 - 1);
                if (this.endPage >= this.totalPage) {
                    this.endPage = this.totalPage;
                    this.startPage = this.totalPage - SHOWPAGES + 1;
                }
            }
        }
    }

    public int getNowPage() {
        return nowPage;
    }

    public void setNowPage(int nowPage) {
        this.nowPage = nowPage;
    }

    public int getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public String getPageHtml2() {
        return pageHtml2;
    }

    public void setPageHtml2(String pageHtml2) {
        this.pageHtml2 = pageHtml2;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public int getStartPage() {
        return startPage;
    }

    public void setStartPage(int startPage) {
        this.startPage = startPage;
    }

    public int getEndPage() {
        return endPage;
    }

    public void setEndPage(int endPage) {
        this.endPage = endPage;
    }
}
import java.io.IOException;
import java.lang.reflect.Type;

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 com.google.gson.reflect.TypeToken;
import com.xukaiqiang.bean.QueryResult;
import com.xukaiqiang.bean.User;
import com.xukaiqiang.dao.UserDao;
import com.xukaiqiang.page.PageViewBaidu;
import com.xukaiqiang.util.Globals;
import com.xukaiqiang.util.Utils;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
{

        int currentPage = Integer.parseInt(request.getParameter("page"));
        // 分页获取所有的用户列表
        UserDao userDao = new UserDao();
        // 分页后的集合
        QueryResult<User> users = userDao.queryUser((currentPage - 1) * Globals.PAGE_NUM, Globals.PAGE_NUM);
        /**
         * 百度分页开始
         */

        PageViewBaidu<User> pageView=new PageViewBaidu<>(currentPage, (int) users.getTotalRecord(), users.getList());
        Type listType = new TypeToken<PageViewBaidu<User>>() {
        }.getType();
    }
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBHelper {

 public static Connection getConn(){
     Connection connection = null;
     try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test""root""root");

    } catch (Exception e) {

        e.printStackTrace();
    }
     return connection;
 }
   public static void closeConn(Connection connection){
        try {
         if (connection != null) {
            connection.close();
           }
        }catch (Exception e) {
            e.printStackTrace();
        }
   }
}
public class Globals {
    /** 每页多少条记录 */
    public static final int PAGE_NUM = 5;

    /**百度分页显示多少索引*/
    public static final int SHOWPAGES = 10;

}
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class Utils {

    public static String printInfo(Object object, HttpServletResponse response,Type listType) {
        //如果是Struts2这里可以使用ServletActionContext.getResponse();获取HttpServletResponse对象
        Gson gson = new Gson();
        String result = gson.toJson(object,listType);
        response.setContentType("text/json; charset=utf-8");
        response.setHeader("Cache-Control""no-cache"); // 取消浏览器缓存
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(result);
        out.flush();
        out.close();
        return null;
    }

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>分页</title>
<!-- 新 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
    //验证用户名是否可以使用
    function query(page{
        //获取用户名
        var userName = $("#userName").val();
        //请求的url
        var dataUrl = "UserServlet";
        //要提交的参数如果是对象可以:"user.userName":userName提交到action
        var params = {
            "userName" : userName,
            "page" : page
        };
        $
                .ajax({
                    async : true,//设置为异步,如果设置为同步,必须等ajax请求完毕之后,再执行进行下面的操作
                    url : dataUrl,//请求的url
                    data : params,//要传递的参数
                    dataType : "json",//返回的数据格式为json
                    cache : false,//不设置缓存
                    type : "POST",//提交方式post
                    //请求出错调用的方法
                    error : function(textStatus, errorThrown{
                        alert("ajax请求失败!");
                    },
                    //请求之前的方法
                    beforeSend : function({
                        //alert("请求前执行的方法!通常放一张加载的图片");
                    },
                    //请求成功的方法,data为返回的数据
                    success : function(data, textStatus{
                        var innerHtml = "<table class='table table-bordered' style='width:50%'>";
                        innerHtml += "<th>编号<th>姓名</th><th>年龄</th>";
                        //$("#msg").html("姓名:" + data.userName + "----年龄:" + data.age);
                        $.each(data.list, function(index, user{
                            innerHtml += "<tr>";
                            innerHtml += "<td>" + user.id + "</td>";
                            innerHtml += "<td>" + user.userName + "</td>";
                            innerHtml += "<td>" + user.age + "</td>";
                            innerHtml += "</tr>";
                        });
                        innerHtml += "</table>";
                        $("#dataList").html("");
                        $("#dataList").html(innerHtml);
                        //$("#pageHTML").html(data.pageHtml);
                        $("#pageHTML2").html(data.pageHtml2);
                    }
                });
    }
</script>
</head>
<body onload="query(1)">
    <center>
        <h2>百度分页</h2>
        <hr>
        <div id="dataList"></div>
        <div id="pageHTML"></div>
        <div id="pageHTML2"></div>
    </center>
</body>
<script>
var a_idx = 0;

    $("body").click(function(e{
        var a = new Array(
            "富强""民主""文明""和谐",
            "自由""平等""公正""法治",
            "爱国""敬业""诚信""友善"
            );
        var $i = $("<span/>").text(a[a_idx]);
        a_idx = (a_idx + 1) % a.length;
        var x = e.pageX,
        y = e.pageY;
        $i.css({
            "z-index"144469,
            "top": y - 20,
            "left": x,
            "position""absolute",
            "font-weight""bold",
            "color""#f00"
        });
        $("body").append($i);
        $i.animate({
            "top": y - 180,
            "opacity"0
        },
        1500,
        function({
            $i.remove()
        })
    });

</script>
</html>

在这里插入图片描述

在这里插入图片描述

发布了37 篇原创文章 · 获赞 53 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_40861561/article/details/84553127