java分页技术

分页技术

页面信息

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>分页</title>
</head>
<body>
    <div style="float: left">
        <span>总页码数:${pageModel.totalPage}</span>
        <span>当前页:${pageModel.currentPage}</span>
        <%-- 使用el表达式内置对象param 通过key值获取value值--%>
        <sapn><a href="${param.path}?currentPage=1">首页</a></sapn>
        <%--
            总记录数 总页码数
            limit a,b
        --%>
        <span>总记录数:${pageModel.totalPage * 5}</span>
    </div>
   <div style="float:right">
    <c:choose>
        <c:when test="${pageModel.currentPage == 1}"><%--上一页逻辑---->是否等于第一页--%>
            <a>上一页</a>
        </c:when>
        <c:otherwise>
            <%--${param.path}----> ${pageContext.request.contextPath}/user/userList?page=--%>
            <a href="${param.path}?currentPage=${pageModel.currentPage -1}">上一页</a>
        </c:otherwise>
    </c:choose>
    <c:forEach begin="${pageModel.beginPage}" end="${pageModel.endPage}" varStatus="status">
            <%--<a href="${pageContext.request.contextPath}/page?">${status.index}</a>--%>
        <c:choose>
            <c:when test="${pageModel.currentPage == status.index}">
                <a style="color: green" >${status.index}</a><%--当前页自然就在中间--%>
            </c:when>
            <c:otherwise>

                <a  href="${param.path}?currentPage=${status.index}">${status.index}</a>
            </c:otherwise>
        </c:choose>
    </c:forEach>
    <c:choose>
        <c:when test="${pageModel.currentPage == pageModel.totalPage}"><%--下一页逻辑是---->判断是否等于总页码数--%>
            <a>下一页</a>
        </c:when>
        <c:otherwise>
            <a href="${param.path}?currentPage=${pageModel.currentPage + 1}">下一页</a>
        </c:otherwise>
    </c:choose>
       <span><a href="${param.path}?currentPage=${pageModel.totalPage}">尾页</a></span>
   </div>
</body>
</html>

德鲁伊连接池

# 连接数据库的组件参数
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///java31?characterEncoding=utf8
username=root
password=root
#初始化池子的连接数量
initialSize=10
#最大池子连接数量
maxActive=50
#最长等待时间
maxWait=3000

tools层工具类

// 德鲁伊连接池数据源工具类
public class DruidDBUtil {
	
	private static DataSource pool;
	
	static {
		// 使用 Properties
		Properties pro = new Properties();
		// 使用Properties集合读取配置文件信息
		InputStream is = DruidDBUtil.class.getClassLoader().getResourceAsStream("db.properties");
		try {
			// 读取配置文件信息
			pro.load(is);
			// 创建连接池
			 pool = DruidDataSourceFactory.createDataSource(pro);
		} catch (Exception e) {
			System.out.println("创建数据源失败!!");
			e.printStackTrace();
		}
	}
	
	// 对外提供获取连接的方法
	public static Connection getConnection() throws SQLException {
		return pool.getConnection();
	}
	
	// 对外获取数据源的方法
	public static DataSource getDataSource() {
		return pool;
	}
	
	// 释放资源
	public static void closeAll(ResultSet set,PreparedStatement ps,Connection conn) {
		if (set != null) {
			try {
				set.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

pool层

// 分页对象 使用泛型扩大使用范围
public class PageModel<T> {

    private int currentPage;// 当前页
    private int beginPage;// 起始页
    private int endPage;// 结束页
    private int totalPage;// 总页码数
    private int pageNum;// 页码数 假定为奇数页
    private List<T> list;


    // 根据当前页去计算起始页和结束页
    private void caluBeginAndEnd(){
        // 写计算起始页和结束页的逻辑  页码数 11 9 7 5 5+4 => 9
        // 先根据当前页计算结束页 ----> 右边的值
        if (currentPage + (pageNum-1)/2 > totalPage){
            // 说明已经到末尾了
            endPage = totalPage;
            // 结束页拿到之后,先推算起始页
            beginPage = endPage - (pageNum - 1) < 1 ? 1 : endPage - (pageNum - 1);// 控制起始页数
        } else{
            // 当前页+5没有大于总页码数
            //先计算起始页
            beginPage = currentPage - (pageNum-1)/2 < 1 ? 1 : currentPage - (pageNum-1)/2;
            endPage = beginPage + (pageNum - 1) > totalPage ? totalPage : beginPage + (pageNum-1);// 控制结束页数
        }
    }

    public PageModel(int currentPage, int totalPage, int pageNum, List<T> list) {
        this.currentPage = currentPage;
        this.totalPage = totalPage;
        this.pageNum = pageNum;
        this.list = list;
        caluBeginAndEnd();
    }

    public PageModel() {
    }

    public int getPageNum() {
        return pageNum;
    }

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

    public int getCurrentPage() {
        return currentPage;
    }

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

    public int getBeginPage() {
        return beginPage;
    }

    public void setBeginPage(int beginPage) {
        this.beginPage = beginPage;
    }

    public int getEndPage() {
        return endPage;
    }

    public void setEndPage(int endPage) {
        this.endPage = endPage;
    }

    public int getTotalPage() {
        return totalPage;
    }

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

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

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

    @Override
    public String toString() {
        return "PageModel{" +
                "currentPage=" + currentPage +
                ", beginPage=" + beginPage +
                ", endPage=" + endPage +
                ", totalPage=" + totalPage +
                ", pageNum=" + pageNum +
                ", list=" + list +
                '}';
}

sevlet层

@WebServlet("/page")
public class TestPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 构建一个分页对象  假定页码数11
        //String page = request.getParameter("page");
        //int currentPage = page == null ? 1:Integer.parseInt(page);

        //PageModel pageModel = new PageModel(currentPage, 100, 11);
        //  5 6 7 8 9 10 11 12 13 14 15
       // request.setAttribute("pageModel", pageModel);
        //request.getRequestDispatcher("/pageInfo.jsp").forward(request, response);
    }

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

连接数据库创user表

public interface UserDao {

    // 总记录数
    int findAllUserCount();
    // 分页的总信息值
    List<User> findAllUser(int currentPage);

}
public class UserDaoImpl implements UserDao {
    // 工具类
    private JdbcTemplate jp =  new JdbcTemplate(DruidDBUtil.getDataSource());

    // 查询总记录数
    @Override
    public int findAllUserCount() {
        long count = 0;
        try{
             count = jp.queryForObject("select count(1) from user",Long.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return (int)count;
    }

    // 查询总记录值
    @Override
    public List<User> findAllUser(int currentPage) {
        // 起始索引值 需要根据当前页判断  b= 5
        // a = currentPage
        // currentpage = 1      a = 0
        //  currentpage = 2     a = 5
        //  ......
        // a = (currentPage-1) * 5
        List<User> list = null;
        try{
            String sql = "select * from user limit ?,5";
             list = jp.query(sql, new BeanPropertyRowMapper<>(User.class), (currentPage - 1) * 5);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

public class User {

    private int u_id;
    private String u_name;
    private String password;
    private String u_phone;

    public int getU_id() {
        return u_id;
    }

    public void setU_id(int u_id) {
        this.u_id = u_id;
    }

    public String getU_name() {
        return u_name;
    }

    public void setU_name(String u_name) {
        this.u_name = u_name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getU_phone() {
        return u_phone;
    }

    public void setU_phone(String u_phone) {
        this.u_phone = u_phone;
    }

    public User(int u_id, String u_name, String password, String u_phone) {
        this.u_id = u_id;
        this.u_name = u_name;
        this.password = password;
        this.u_phone = u_phone;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "u_id=" + u_id +
                ", u_name='" + u_name + '\'' +
                ", password='" + password + '\'' +
                ", u_phone='" + u_phone + '\'' +
                '}';
    }
}
public interface UserService {
    // 组装分页对象
    PageModel<User> loadPage(int currentPage);

}
public class UserServiceImpl implements UserService {

    // 属性注入
    private UserDao ud = new UserDaoImpl();

    @Override
    public PageModel<User> loadPage(int currentPage) {
        // 拼装分页对象  pageModel
        // 总记录数 ---->totalPage
        int  count  = ud.findAllUserCount();
        System.out.println(count+"---------");
        // 总信息值(分页查询 根据当前页查询的总信息值) list<User>
        List<User> list = ud.findAllUser(currentPage);
        System.out.println(list.size()+"-------");
        // 每页查询5条  ----> b = 5       totalPage = count % 5 == 0 ? count / 5 : count/5+1
        // totalPage = (count + 4 ) / 5
        // 5 6  11
        // 组装page对象  pageNum =  11
        PageModel<User> page = new PageModel<User>(currentPage, (count + 4 ) / 5, 11, list);
        return page;
    }
}
@WebServlet("/user/userList")
public class UserListServlet extends HttpServlet {
    // 属性注入
    private UserService us = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前页
        String currentPage = request.getParameter("currentPage");
        int currNum = currentPage == null ? 1:Integer.parseInt(currentPage);
        // 组装分页对象  List<User> ----> 装配的是对应模块的信息值
        // new PageModel(beginPage,endPage,currentPage,totalPage,List)---->逻辑放到service层

        // 调用组装好的service方法 来获取分页对象
        PageModel<User> page =  us.loadPage(currNum);
        // 把page对象存进到域中
        request.setAttribute("pageModel", page);
        request.getRequestDispatcher("/userList.jsp").forward(request, response);

    }

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值