分页思路:
将上一次查询请求再发一次,只不过页码变了
具体思路:
1、补全servlet
2、页面展示
3、分页重要参数(page、rows、是否分页、上一次请求、上一次的表单参数)
4、自定义分页标签
首先呢 我们在java编译的过程中 会遇到乱码的一些情况 我们都是在乱码的地方给它设置编码格式就可以了 但是如果每一次都要给它设置 就会显得麻烦 所以我们这里写一个处理中文乱码的工具类。
1.EncodingFiter.java(处理中文乱码的帮助类):
代码如下:
package com.LHJ.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();
}
}
}
写好之后记得配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>web_tyfy</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.LHJ.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<!--*代表目录下的所有文件 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.创建一个pageBean分页类,并对这个类增加属性和封装方法:
代码如下:
package com.LHJ.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 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;
}
}
3.bookServlet(业务逻辑处理层):
代码如下:
package com.LHJ.Servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.LHJ.dao.BookDao;
import com.LHJ.entity.Book;
import com.LHJ.util.PageBean;
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = -3310464183891193669L;
private BookDao bookDao = new BookDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String bname = req.getParameter("bname");
Book book = new Book();
book.setBname(bname);
//得到传来的所有name名和name所代表的的value值
// 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) {
e.printStackTrace();
}
}
}
然后记得配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>web_tyfy</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.LHJ.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.LHJ.Servlet.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bookservlet</servlet-name>
<url-pattern>/bookServlet</url-pattern>
</servlet-mapping>
</web-app>
4.自定义标签类PageTag:
代码如下:
package com.LHJ.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 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;
}
}
然后编写tld文件:
如下:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>lhj 1.1 core library</description>
<display-name>lhj core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>c</short-name>
<uri>/lhj</uri>
<tag>
<!-- 标签库中的标签 (类似c:set c:out的定义) -->
<name>page</name>
<!-- 是标签运行具体代码,也就是助手类,下面填写的助手类的全路径名 -->
<tag-class>com.LHJ.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="z" uri="/lhj" %>
<!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="确定">
<!-- <input type="hidden" name="pagination" value="false"> -->
<input type='hidden' name="rows" value="20">
</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>
运行结果如下: