分頁筆記-servlet版

導包
鏈接:https://pan.baidu.com/s/1uLVyJrOKcHRFGNaPEBZ6KA
提取碼:rw5f

這條博客只是給自己做個筆記,由於裏面的方法提取的不夠統一,不建議參照。。。。

servlet代碼

UserService userService = new UserService();
    public String selectStaff(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	Map<String, String[]> map = request.getParameterMap();
    	//這個就是把前端表單發過來的數據一一放進page裏面,相當於多個request.getParameter
    	Page page = CommonUtils.toBean(map, Page.class);
        List<Staff> list = userService.selectStaff(page);
        //設置數據總條數
        page.setTotal(userService.count());
        request.setAttribute("page", page);
        request.setAttribute("userList",list);
        return "f:user.jsp";
    }

service代碼

UserDao userDao = new UserDao();
public List<Staff> selectStaffByD(String depName){
        List<Staff> list = userDao.selectByD(depName);
        return list;
    }
     public int count(){
    	return userDao.count();
    }

dao代碼

public List<Staff> selectStaff(Page page){
        List<Staff> list = new ArrayList<>();
        Connection con = DBUtil.getConnection();
        PreparedStatement ptmt = null;
        ResultSet res = null;
        //主要要注意這裏的limit,其他的亂七八糟的都要改
        String sql = "SELECT * FROM crm_staff,crm_post,crm_department "
        		+ "WHERE crm_staff.postID=crm_post.id "
        		+ "AND crm_post.depID=crm_department.id  order by crm_staff.id "
        		+ "limit ?,?";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            ptmt = con.prepareStatement(sql);
            ptmt.setInt(1, page.getStart());
            ptmt.setInt(2, page.getCount());
            res = ptmt.executeQuery();
            while(res.next()){
                Staff staff = new Staff();
                staff.setStaffName(res.getString("staffName"));
                staff.setGender(res.getString("gender"));
                Date d = res.getDate("onDutyDate");
                staff.setOnDutyDate(simpleDateFormat.format(d.getTime()));
                staff.setDepName(res.getString("depName"));
                staff.setPostName(res.getString("postName"));
                staff.setId(res.getInt("id"));
                list.add(staff);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
public int count(){
    	 Connection con = DBUtil.getConnection();
         PreparedStatement ptmt = null;
         ResultSet res = null;
         int count = 0;
         String sql = "SELECT count(*) FROM crm_staff,crm_post,crm_department "
         		+ "WHERE crm_staff.postID=crm_post.id "
         		+ "AND crm_post.depID=crm_department.id";
         
         try {
        	ptmt = con.prepareStatement(sql);
			res = ptmt.executeQuery();
			if(res.next()){
				count = res.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         return count;
         
    }

前端代碼,只要在jstl循環後面加上這個jsp片段就可以實現分頁效果,記得要把bootstrap導進去



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


 
<script>
$(function(){
    $("ul.pagination li.disabled a").click(function(){
        return false;
    });
});
 
</script>
 
<nav>
  <ul class="pagination">
    <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
      <a  href="?method=selectStaff&start=0${page.param}" aria-label="Previous" >
        <span aria-hidden="true">«</span>
      </a>
    </li>
 
    <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
      <a  href="?method=selectStaff&start=${page.start-page.count}${page.param}" aria-label="Previous" >
        <span aria-hidden="true"></span>
      </a>
    </li>   
 
    <c:forEach begin="0" end="${page.totalPage-1}" varStatus="status">
                <c:if test="${status.count*page.count-page.start<=20 && status.count*page.count-page.start>=-10}">
    
	                <li <c:if test="${status.index*page.count==page.start}">class="disabled"</c:if>>
	                <a
	                href="?method=selectStaff&start=${status.index*page.count}${page.param}"
	                <c:if test="${status.index*page.count==page.start}">class="current"</c:if>
	                >${status.count}</a>
	            </li>
	            
            </c:if>
         
    </c:forEach>
 
    <li <c:if test="${!page.hasNext}">class="disabled"</c:if>>
      <a href="?method=selectStaff&start=${page.start+page.count}${page.param}" aria-label="Next">
        <span aria-hidden="true"></span>
      </a>
    </li>
    <li <c:if test="${!page.hasNext}">class="disabled"</c:if>>
      <a href="?method=selectStaff&start=${page.last}${page.param}" aria-label="Next">
        <span aria-hidden="true">»</span>
      </a>
    </li>
  </ul>
</nav>

page類

public class Page {

    private int start; //開始頁數
    private int count; //每頁顯示個數
    private int total; //總個數
    private String param; //參數

    private static final int defaultCount = 5; //默認每頁顯示5條

    public int getStart() {
        return start;
    }
    public void setStart(int start) {
        this.start = start;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }

    public Page (){
        count = defaultCount;
    }
    public Page(int start, int count) {
        super();
        this.start = start;
        this.count = count;
    }

    public boolean isHasPreviouse(){
        if(start==0)
            return false;
        return true;
    }
    public boolean isHasNext(){
        if(start==getLast())
            return false;
        return true;
    }

    public int getTotalPage(){
        int totalPage;
        // 假設總數是50,是能夠被5整除的,那麼就有10頁
        if (0 == total % count)
            totalPage = total /count;
            // 假設總數是51,不能夠被5整除的,那麼就有11頁
        else
            totalPage = total / count + 1;

        if(0==totalPage)
            totalPage = 1;
        return totalPage;

    }

    public int getLast(){
        int last;
        // 假設總數是50,是能夠被5整除的,那麼最後一頁的開始就是45
        if (0 == total % count)
            last = total - count;
            // 假設總數是51,不能夠被5整除的,那麼最後一頁的開始就是50
        else
            last = total - total % count;
        last = last<0?0:last;
        return last;
    }

    @Override
    public String toString() {
        return "Page [start=" + start + ", count=" + count + ", total=" + total + ", getStart()=" + getStart()
                + ", getCount()=" + getCount() + ", isHasPreviouse()=" + isHasPreviouse() + ", isHasNext()="
                + isHasNext() + ", getTotalPage()=" + getTotalPage() + ", getLast()=" + getLast() + "]";
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public String getParam() {
        return param;
    }
    public void setParam(String param) {
        this.param = param;
    }

}

總結:前端直接把代碼加進去就行,servlet裏面需要一直更新page的值,dao需要一個select裏面有limit的方法和一個count(*)的方法,這樣就可以實現分頁了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章