码迷,mamicode.com
首页 > 其他好文 > 详细

通用分页2

时间:2019-06-23 01:06:53      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:sub   comment   获得   let   path   final   表达   vat   mono   

上次我们的通用分页只能在后台显示,我们完善一下上次的后台代码,把它做成一个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方法:

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);
                
        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();
        }
    }
     
}

创建一个过滤器处理中文乱码:

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 中文乱码处理
 *
 */
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();
        }
    }
 
}

创建一个自定义标签类:

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) {
                //上一次请求可能携带页码naempage得参数,但是改参数在前面以及单独赋值
                //为什么要单独赋值?因为上一次请求时第一页得数据,下一次可能时第二页,以后这前后请求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+"‘>");
                    }
                }
            }
        }<br><br>
        sb.append("</form>");
        //拼接分页条
        sb.append("<div style=‘text-align: right; font-size: 12px;‘>");
        sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页  <a ");
        sb.append(" href=‘javascript:gotoPage(1)‘>首页</a>  <a");
        sb.append(" href=‘javascript:gotoPage("+pageBean.getpreviousPage()+")‘>上一页</a>  <a");
        sb.append(" href=‘javascript:gotoPage("+pageBean.getNextPage()+")‘>下一页</a>  <a");
        sb.append(" href=‘javascript:gotoPage("+pageBean.getMaxPage()+")‘>尾页</a>  <input type=‘text‘");
        sb.append(" id=‘skipPage‘");
        sb.append(" style=‘text-align: center; font-size: 12px; width: 50px;‘>  <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();
    }
}

配置xml文件:

<filter>
  <filter-name>encodingFiter</filter-name>
  <filter-class>com.util.EncodingFiter</filter-class>
</filter> <filter-mapping> <filter-name>encodingFiter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>bookServlet</servlet-name> <servlet-class>com.web.BookServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>bookServlet</servlet-name> <url-pattern>/bookServlet</url-pattern> </servlet-mapping>

配置tld文件导入自定义标签:

<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
   "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>m</short-name>
    <uri>/myjsp</uri>
<!--   标签库中的标签(类似c:set c:out的定义) -->
    <name>page</name>
   <!--  是标签运行具体代码,也就是助手类,下面填写的是助手类的全路径 -->
    <tag-class>com.tag.PageTag</tag-class>
<body-content>JSP</body-content> <attribute> <!-- 该标签的属性 --> <name>pageBean</name>    <!-- 该属性是否必填 --> <required>true</required>    <!-- 是否支持表达式 --> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
 

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="m" uri="/myjsp" %>
<!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>
<m:page pageBean="${pageBean }"></m:page>
</body>
</html>

运行结果如下:

技术图片

 

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();
        }
    }
     
}

 

通用分页2

标签:sub   comment   获得   let   path   final   表达   vat   mono   

原文地址:https://www.cnblogs.com/huxiaocong/p/11070924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!