通用分页二

 

这次主要是将分页体现在JSP页面上,上一篇只是完成后台的分页

首先我们来完善一下pagebean页面的内容

public class PageBean {

    private int page = 1;// 页码

    private int rows = 10;// 页大小

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

    private boolean pagination = true;// 是否分页
    private Map<String,String[]> paMap=new HashMap<>();
    private String url;
    public void setRequest(HttpServletRequest req) {
        
        //保存上一次请求所携带得参数
        this.setPaMap(req.getParameterMap());
        this.setUrl(req.getRequestURI().toString());
        //在jsp页面来控制是否分页
        this.setPagination(req.getParameter("pagination"));
        //在jsp页面控制一页展示多少条数据
        this.setRows(req.getParameter("rows"));
        this.setPage(req.getParameter("page"));
    }
    public void setPage(String page) {
        this.page=StringUtils.isNotBlank(page)?Integer.valueOf(page):this.page;
    }
    
    public void setPagination(String pagination) {
        this.pagination=StringUtils.isNotBlank(pagination)?!"false".equals(pagination):this.pagination;
    }

    public void setRows(String rows) {
        this.rows=StringUtils.isNotBlank(rows)?Integer.valueOf(rows):this.rows;
        
    }

    public Map<String, String[]> getPaMap() {
        return paMap;
    }

    public void setPaMap(Map<String, String[]> paMap) {
        this.paMap = paMap;
    }

    public String getUrl() {
        return url;
    }

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

    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 + "]";
    }
    /**
     * 获取最大的页码数
     * @return
     */
    public int getMaxPage() {
        return this.total%this.rows==0 ? this.total/this.rows : this.total/this.rows+1;
    }
    /**
     * 获取下一页
     * @return
     */
    public int getNextPage() {
        return this.page < this.getMaxPage() ? this.page+1:this.page;
    }
    /**
     * 获取上一页
     * @return
     */
    public int getpreviousPage() {
        return this.page>1 ? this.page-1:this.page;
    }
}

接下来在新建servlet的方法

BookServlet

package com.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entity.Book;
import com.jt.dao.BookDao;
import com.util.PageBean;

@WebServlet("/bookServlet")
public class BookServlet extends HttpServlet {

    
    private static final long serialVersionUID = 6304839939800249916L;
    private BookDao bookDao=new BookDao();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String bname=req.getParameter("bname");
        Book book=new Book();
        book.setBname(bname);
        
//        Map<String,String[]> parameterMap=req.getParameterMap();
//        StringBuffer url= req.getRequestURL();
        
        
        PageBean pageBean=new PageBean();
        try {
            pageBean.setRequest(req);
            List<Book> list= this.bookDao.list(book, pageBean);
            req.setAttribute("bookList", list);
            req.setAttribute("pageBean",pageBean);
            req.getRequestDispatcher("/BookList.jsp").forward(req, resp);
        } catch (InstantiationException | IllegalAccessException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}

下面就是PageTag类了

也是我们的标签类

package com.tag;

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

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

import com.util.PageBean;

public class PageTag extends BodyTagSupport {

    private static final long serialVersionUID = -553969530960334073L;

    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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return super.doStartTag();
    }

    private String toHTML() {
        // TODO Auto-generated method stub
        StringBuilder sb=new StringBuilder();
        //拼接下一次发送请求所要提交得隐藏得form表单
        sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
        sb.append(" <input type='hidden' name='page'>");
        Map<String, String[]> paMap = pageBean.getPaMap();
        if(paMap!=null&&paMap.size()>0) {
            Set<Entry<String, String[]>> entrySet = paMap.entrySet();
            for (Entry<String, String[]> entry : entrySet) {
                //上一次请求可能携带页码namepage得参数,但是改参数在前面以及单独赋值
                //为什么要单独赋值?因为上一次请求时第一页得数据,下一次可能时第二页,以后这前后请求page对应得值不一样,需要单独赋值
                if(!"page".equals(entry.getKey())) {
//                    <input type='hidden' name='hobby' value='1'>
//                    <input type='hidden' name='hobby' value='2'>
                    //[1,2]
                    for(String val:entry.getValue()) {
                        sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>");
                    }
                }
            }
        }

        sb.append("</form>");
        //拼接分页条
        sb.append("<div style='text-align: right; font-size: 12px;'>");
        sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页&nbsp;&nbsp;<a ");
        sb.append(" href='javascript:gotoPage(1)'>首页</a>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:gotoPage("+pageBean.getpreviousPage()+")'>上一页</a>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a>&nbsp;&nbsp;<input type='text'");
        sb.append(" id='skipPage'");
        sb.append(" style='text-align: center; font-size: 12px; width: 50px;'>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:skipPage()'>Go</a>");
        sb.append("</div>");
        //拼接分页所需要得js代码
        sb.append("<script type='text/javascript'>    ");
        sb.append("function gotoPage(page) {");
        sb.append("document.getElementById('pageBeanForm').page.value = page;");
        sb.append("document.getElementById('pageBeanForm').submit();");
        sb.append("}");
        sb.append("function skipPage() {");
        sb.append("var page = document.getElementById('skipPage').value;");
        sb.append("if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+"){");
        sb.append("alert('请输入1~N的数字');");
        sb.append("return;");
        sb.append("}");
        sb.append("gotoPage(page);");
        sb.append("}");
        sb.append("</script>");
    
        
        return sb.toString();
    }
}

还有一个就是我们的过滤器也是非常重要的

EncodingFiter
package com.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(urlPatterns="/*")
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();
        }
    }

}

现在去jsp页面传值就可以了

把我们自定义的标签导进去

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="z" uri="/jt" %>
<!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>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
    <br>

    <form action="${pageContext.request.contextPath}/bookServlet"
        method="post">
        书名:<input type="text" name="bname"> <input type="submit"
            value="确定">
    </form>
    <table border="1" width="100%">
        <tr>
            <td>编号</td>
            <td>名称</td>
            <td>价格</td>
        </tr>
        <c:forEach items="${bookList }" var="b">
            <tr>
                <td>${b.bid }</td>
                <td>${b.bname }</td>
                <td>${b.price }</td>
            </tr>
        </c:forEach>
    </table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>

大家肯定会说不用配XML?我采用的是一种更加方便的方法

@WebServlet("/bookServlet")

@WebFilter(urlPatterns="/*")

就这2条代码,和XML里面的配置效果是一样的,这样也方便点

来让我们看下运行结果

首页

下一页

尾页

查询

跳转

 

接下来我们就来试试我们的通用分页

我用另一个数据表来调用下

新建servlet类

BlogServlet

package com.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entity.Blog;
import com.jt.dao.BlogDao;
import com.util.PageBean;
@WebServlet("/blogServlet")
public class BlogServlet extends HttpServlet {
    private BlogDao blogDao=new BlogDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        Blog blog=new Blog();
        blog.setBookname(req.getParameter("bookname"));
        PageBean pageBean=new PageBean();
        try {
            List<Blog> list = this.blogDao.list(blog, pageBean);
            req.setAttribute("blogList",list);
            req.setAttribute("pageBean",pageBean);
            req.getRequestDispatcher("/BlogList.jsp").forward(req, resp);
        } catch (InstantiationException | IllegalAccessException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <%@taglib prefix="z" uri="/jt" %>
<!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>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
    <br>

    <form action="${pageContext.request.contextPath}/blogServlet"
        method="post">
        书名:<input type="text" name="bname"> <input type="submit"
            value="确定">
    </form>
    <table border="1" width="100%">
        <tr>
            <td>编号</td>
            <td>名称</td>
        </tr>
    <c:forEach items="${blogList }" var="b">
            <tr>
                <td>${b.id }</td>
                <td>${b.bookname }</td>
            </tr>
        </c:forEach>
    </table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>

改下foreach里面的就可以了,通用分页调用就是这么简单了

 

posted @ 2019-06-22 13:14  youshutup  阅读(212)  评论(0编辑  收藏  举报