通用分页02(前台分页)

  • 分页的核心思想
  • 优化pageBean
  • 分页标签的制作过程

分页的核心思想

http://loccalhost:8080/mvc/book.action?bname=圣墟

1.第一次查询

为什么点击上面链接,显示的是第一页的数据,而不是第二页第三页的数据?

原因:pageBean默认 page=1,rows=10,pagination=true

2.第二次查询

pageBean page=2,rows=10,pagination=true

3.第三次查询

pageBean page=3,rows=10,pagination=true

4.结论优化pageBean:分页就是将上一次请求再发一次,只是页码变了,其他查询条件不变

优化pageBean

 增加一个属性url,保留上一次发送的请求地址

增加一个属性paramMap,保留上一次发送的请求携带的参数,req.getParameterMap();

增加一个最大页的方法

增加一个下一页的方法

增加一个上一页的方法

初始化pageBean的方法

package com.zhulinjun.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
//	增加一个最大页的方法
	public int maxPage() {
		return this.total % this.rows ==0?
				this.total / this.rows:
					this.total / this.rows+1;
	}
//	增加一个下一页的方法
	public int nextPage() {
    	return this.page < this.maxPage() ?
    			this.page+1 : this.page;
    }
//	增加一个上一页的方法
    public int prevPage() {
    	return this.page > 1 ? this.page -1 : this.page;
    } 
    public void setRequest(HttpServletRequest req) {
//    	初始化默认查询第几页的数据(初始化pageBean的方法)
    	this.setPage(req.getParameter("page"));
    	this.setRows(req.getParameter("rows"));
    	this.setPagination(req.getParameter("pagination")); 
//    	保留上一次的url(增加一个属性url,保留上一次发送的请求地址)
    	this.setUrl(req.getRequestURL().toString());
//    	保留携带的参数(增加一个属性paramMap,保留上一次发送的请求携带的参数)
    	this.setParamMap(req.getParameterMap());
    }
    
	public void setPage(String page) {
    	if(StringUtils.isNotBlank(page)) {
    		this.setPage(Integer.valueOf(page));
    	}
    }
    public void setRows(String rows) {
    	if(StringUtils.isNotBlank(rows))
    		this.setRows(Integer.valueOf(rows));
    }
    public void setPagination(String pagination) {
		if(StringUtils.isBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	}
    
	private String url;
	private Map paramMap;
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map paramMap) {
		this.paramMap = paramMap;
	}

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

}

分页标签的制作过程

package com.zhulinjun.tag;


import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.zhulinjun.util.PageBean;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @author 小李飞刀
 * @site www.zking.com
 */
public class tag extends BodyTagSupport {
    private PageBean pageBean;



    public PageBean getPageBean() {
        return pageBean;
    }

    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }

    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            out.print(toHTML());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }

    private String toHTML() {
        StringBuilder sb = new StringBuilder();

//        这里拼接的是一个上一次发送的请求以及携带的参数,唯一改变的就是页码
        sb.append("
"); sb.append(""); sb.append(""); // 重要设置拼接操作,将上一次请求参数携带到下一次 Map paMap = pageBean.getParamMap(); if(paMap !=null && paMap.size()>0){ Set> entrySet = paMap.entrySet(); for (Map.Entry entry : entrySet) { for (String val : entry.getValue()) { if(!"page".equals(entry.getKey())){ sb.append(""); } } } } sb.append(""); int page = pageBean.getPage(); int max = pageBean.maxPage(); int before = page > 4 ? 4 : page-1; int after = 10 - 1 - before; after = page+after > max ? max-page : after; // disabled boolean startFlag = page == 1; boolean endFlag = max == page; // 拼接分页条 sb.append("
    "); sb.append("
  • 首页
  • "); sb.append("
  • <
  • "); // 代表了当前页的前4页 for (int i = before; i > 0 ; i--) { sb.append("
  • "+(page-i)+"
  • "); } sb.append("
  • "+pageBean.getPage()+"
  • "); // 代表了当前页的后5页 for (int i = 1; i <= after; i++) { sb.append("
  • "+(page+i)+"
  • "); } sb.append("
  • >
  • "); sb.append("
  • 尾页
  • "); sb.append("
  • 到第
  • "); sb.append("
  • 确定
  • "); sb.append("
  • 共"+pageBean.getTotal()+"条
  • "); sb.append("
"); // 拼接分页的js代码 sb.append(""); return sb.toString(); } }



    
  JSTL 1.1 core library
  JSTL core
  1.1
  z
  http://jsp.veryedu.cn

  
    page
    com.zhulinjun.tag.tag
    JSP
    
        pageBean
        true
        true
    
  

package com.zking.servlet;
import java.io.IOException;
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 com.zhulinjun.dao.BookDao;
import com.zhulinjun.entity.Book;
import com.zhulinjun.util.PageBean;
@WebServlet("/book.action")
public class BookServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);

}

@SuppressWarnings("unused")
@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//	String bname = req.getParameter("bname");
	map包含了浏览器传递到后台的所有参数键值对
//	Map parameterMap = req.getParameterMap();
	浏览器请求的地址
//	String url = req.getRequestURI().toString();
	PageBean pageBean=new PageBean();
	pageBean.setRequest(req);
	BookDao bookDao=new BookDao();
	Book book = new Book();
	book.setBname(req.getParameter("bname"));
	try {
		List books = bookDao.list(book, pageBean);
		req.setAttribute("books", books);
//		System.out.println(books);

	} catch (Exception e) {
		e.printStackTrace();
	}
	
	req.setAttribute("pageBean", pageBean);
	System.out.println(pageBean);
    req.getRequestDispatcher("bookList.jsp").forward(req, resp);
}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
	<%@taglib prefix="z" uri="http://jsp.veryedu.cn"%>






书籍列表



	 
书籍ID 书籍名 价格
${b.bid } ${b.bname } ${b.price }
package com.zhulinjun.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 中文乱码处理
 * 
 */
@WebFilter("*.action")
public class EncodingFiter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFiter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			Set set = map.keySet();// 取出所有参数名
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

注:结合后台分页上一篇博客的代码

你可能感兴趣的:(java,前端,javascript)