通用分页(二)
1、网页显示分页
第一篇 通用分页一 是在客户端显示控制数据条数,在PageBean 分页工具类。他也是这个类里的核心。但是没有按钮可以换页。这次是在网页中显示数据,也有分页的效果。
注意:如果是用mysql数据库,还不知道怎么连接的可以点击上面的连接里面有。
具体思路:
1、补全servlet
2、页面展示
3、分页重要参数(page、rows、是否分页、上一次请求、上一次的表单参数)
4、自定义分页标签
如何将上一次查询请求再发一次
String contextPath = req.getContextPath();//根目录
String url = req.getServletPath();//请求的地址
req.getRequestURL() //获取请求全路径
Map<String, String[]> parameterMap = req.getParameterMap();//获得请求中的所有参数
PageBean( 分页工具类)
package com.DZY.util1;
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 boolean pagination = true;// 是否分页
private Map<String, String[]> paMap=new HashMap<>();
private String url;
public void setRequest(HttpServletRequest req) {
//保存上一次请求携带的参数
// getParameterMap可以获取到一次url请求所携带的所有参数
this.setPaMap(req.getParameterMap());
// getRequestURL获取到浏览器请求的全路径
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) {
if(StringUtils.isNotBlank(page)) {
this.setPage(Integer.valueOf(page));
}
//this.page=StringUtils.isNotBlank(page) ? Integer.valueOf(page) :this.page;
}
public void setPagination(String pagination) {
if("false".equals(pagination)) {
this.setPagination(false);
}
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.setRows(Integer.valueOf(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;
}
/**
* 获取上一页的页码数
*/
public int getPreviousPage() {
return this.page>1 ? this.page-1:this.page;
}
}
EncodingFiter类(中文乱码处理)
package com.DZY.util1;
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();
}
}
}
StringUtils类
package com.DZY.util1;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
PageTag类
package com.DZY.util1;
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;
public class PageTag extends BodyTagSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private PageBean pageBean;
public PageBean getPageBean() {
return pageBean;
} public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
} public static long getSerialversionuid() {
return serialVersionUID;
}
@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='"+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) {
//上一次请求可能携带页码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("每页"+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>");
//拼接分页所需要的jsp代码
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();
}
}
web配置
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.DZY.util1.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.DZY.Servlet.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bookServlet</servlet-name>
<url-pattern>/bookServlet</url-pattern>
</servlet-mapping>
z.tld配置
<description>DZY 1.1 core library</description>
<display-name>DZY core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>z</short-name>
<uri>/DZY</uri>
<tag>
<!-- 标签库中的标签(类似c:set c:out的定义) -->
<name>page</name>
<!-- 是标签运行具体代码,也就是助手类,下面填写的是助手类的全路径 -->
<tag-class>com.DZY.util1.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<!-- 该标签的属性 -->
<name>pageBean</name>
<!-- 该属性是否必填 -->
<required>true</required>
<!-- 是否支持表达式 -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
BookServlet类
package com.DZY.Servlet;
import java.io.IOException;
import java.sql.SQLException;
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.DZY.dao1.*;
import com.DZY.entity1.*;
import com.DZY.util1.*;
//*号代表这个包里的全部
public class BookServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
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 {
String bname=req.getParameter("bname");
//直接从这运行的话,bname会等于null;所以if
if(bname==null) {
bname="";
}
Book book=new Book();
book.setBname(bname);
// Map<String,String[]> parameterMap=req.getParameterMap();
// StringBuffer url= req.getRequestURL();
PageBean pageBean=new PageBean();
// System.out.println(pageBean);
try {
pageBean.setRequest(req);
List<Book> list= this.bookDao.list(book, pageBean);
req.setAttribute("pageBean", pageBean);
req.setAttribute("bookList", list);
req.getRequestDispatcher("/Demo.jsp").forward(req, resp);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Demo.jsp(显示页面)
<c:if test="${bookList==null }">
<c:redirect url="bookServlet"></c:redirect>
</c:if>
<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>
显示效果:
模糊查询效果: