zoukankan      html  css  js  c++  java
  • 通用分页2

    1.首页在我们通用分页1博客的基础上新建Servlet

    package com.hmc.web;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.Servlet;
    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.hmc.dao.BookDao;
    import com.hmc.entity.Book;
    import com.hmc.util.PageBean;
    
    /**
     * Servlet implementation class BookServet
     */
    @WebServlet("/BookServet")
    public class BookServet extends HttpServlet implements Servlet {
    	private static final long serialVersionUID = 1L;
        private BookDao bookDao=new BookDao(); 
    	
        /**
         * @see HttpServlet#HttpServlet()
         */
        public BookServet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
       doPost(request, response);
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stubo
       String bname=request.getParameter("bname");
       Book book=new Book();
       book.setBname(bname);
       PageBean bean=new PageBean();
      
       try {
    	   bean.setRequest(request);
    	List<Book> list=this.bookDao.list(book, bean);
       request.setAttribute("booklist", list);
       request.setAttribute("pagebean",bean);
      
       request.getRequestDispatcher("/book.jsp").forward(request, response);
       } catch (Exception e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    	
    	}
    
    }
    

      

     2.改造PageBen

    package com.hmc.util;
    
    import java.util.HashMap;
    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 Map<String, String[]> paMap=new HashMap<String, String[]>();
    	private String url;
    	
    	
       public void setRequest(HttpServletRequest request) {
    	  
    	   //保存上一次请求的所有参数
    	   this.setPaMap( request.getParameterMap());
           this.setUrl(request.getRequestURL().toString());
           //在jsp页面来控制是否分页
           this.setPagination(request.getParameter("pagination"));
            //在jsp页面控制一页展示多少条
           this.setRows(request.getParameter("rows"));
           this.setPage(request.getParameter("page"));
       }
    	 
    	private void setPage(String page) {
      	this.page=StringUtils.isNotBlank(page) ? Integer.valueOf(page) : this.page;
    }
    
    	private void setPagination(String pagination) {
         this.pagination=StringUtils.isNotBlank(pagination) ? !"false".equals(pagination) : this.pagination;
         
    }
    
    	private 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;
    	}
    
    	private boolean pagination = true;// 是否分页
    
    	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;
       }
    	
    }
    

     3 创建自定义分页标签

    3.1

    新建助手类PageTag.java

    package com.hmc.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.hmc.util.PageBean;
    
    public class PageTag extends  BodyTagSupport {
    	
    	
    	private PageBean bean;
    
    	public PageBean getBean() {
    		return bean;
    	}
    
    	public void setBean(PageBean bean) {
    		this.bean = bean;
    	}
    	
    	@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() {
    		StringBuilder sb=new StringBuilder();
    		//拼接下一次发送请求所要提交的隐藏的form表单
    	   sb.append("<form id='pageBeanForm' action='"+bean.getUrl()+"' method='post'>");
    	   sb.append(" <input type='hidden' name='page'>");
    	  
    	   Map<String, String[]> paMap = bean.getPaMap();
    	   if(paMap!=null&&paMap.size()>0) {
    		   Set<Entry<String, String[]>> entrySet = paMap.entrySet();
    	   for (Entry<String, String[]> entry : entrySet) {
    	   //上一次请求可能携带页面name=page的参数,但是改参数在前面已经单独赋值
    	//为什么要单独赋值呢?因为上一次请求是第一页的数据,下一次可能是第二页,因为这前后请求page对应的值是不一样的,要单独赋值
    		   if(!"page".equals(entry.getKey())) {
    			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(" 每页"+bean.getRows()+"条,共"+bean.getTotal()+"条,第"+bean.getPage()+"页,共"+bean.getMaxPage()+"页  <a href='javascript:gotoPage(1)'>首页");
    	   sb.append(" </a>  <a");
    	   sb.append(" href='javascript:gotoPage("+bean.getPreviousPage()+")'>上一页</a>  <a");
    	   sb.append(" href='javascript:gotoPage("+bean.getNextPage()+")'>下一页</a>  <a");
    	   sb.append(" href='javascript:gotoPage("+bean.getMaxPage()+")'>尾页</a>  <input type='text'");
    	   
    	   sb.append(" id='skipPage'");
    	   sb.append(" style='text-align: center; font-size: 12px;  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)>"+bean.getMaxPage()+"){");
    	   sb.append("    alert('请输入1~N的数字');");
    	   sb.append("    return;");
    	   sb.append(" }");
    	   sb.append("   gotoPage(page);");
    	   sb.append("}");
    	   sb.append("</script>");
    	   return sb.toString();
    	
    	}
    }
    

      3.2创建tld文件index.tld(要与助手类的属性一一对应)

    <tag>
      <name>page</name>
      <tag-class>com.hmc.tag.PageTag</tag-class>
      <body-content>JSP</body-content>
      <attribute>
        <name>bean</name>
         <required>true</required>
         <rtexprvalue>true</rtexprvalue>
      </attribute>
      </tag>
    

      

    4.掉用过滤器EncodingFiter.java处理中文乱码问题

    @WebFilter(urlPatterns="/*")使用的是servlet3.0注解技术。
    package com.hmc.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();
    		}
    	}
    
    }
    

      5.新建jsp进行测试

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%@page isELIgnored="false" %>
        <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
        <%@taglib prefix="z" 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}/BookServet"
    		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 bean="${pagebean }"></z:page>
    	
    </body>
    </html>
    

      结果如下

    所有数据展示

    模糊查询结果

    查询所有的第二页数据

     尾页数据

     这就是一个整体的一个单表通用分页效果

    主要就是将上一次查询请求再发一次
    String contextPath = req.getContextPath();//根目录
    String url = req.getServletPath();//请求的地址
    req.getRequestURL() //获取请求全路径
    Map<String, String[]> parameterMap = req.getParameterMap();//获得请求中的所有参数

      注1:不能将分页表单嵌套到其它表单中,否则不能提交表单!!!

  • 相关阅读:
    PAT 甲级 1115 Counting Nodes in a BST (30 分)
    PAT 甲级 1114 Family Property (25 分)
    PAT 甲级 1114 Family Property (25 分)
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
  • 原文地址:https://www.cnblogs.com/xmf3628/p/11069982.html
Copyright © 2011-2022 走看看