分页技术就是通过SQL语句(如下)来获取数据,具体实现看下面代码
//分页查询语句
select * from 表名 where limit page , count;
和
//获取表中的总数据,确定页数
select count(*) from 表名;
在项目的WebContent/META-INF目录下创建一个context.xml文件。如图:
在context.xml文件中配置:
<Context>
<Resource name="jdbc/bookstore" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/db_bookstore"/>
Context>
这里采用的是Javaweb自带的DBCP配置,详细参考Javaweb配置常用的数据源配置
public class DBUtils {
public static Connection getConn(){
try {
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:/comp/env/jdbc/bookstore");
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn){
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public interface BookDao {
public List findBooks(int page , int count) throws SQLException;
public int count() throws SQLException;
}
public class BookDaoImpl implements BookDao{
private Connection conn = DBUtils.getConn();
@Override
public List findBooks(int page, int count) throws SQLException {
if(conn==null){
throw new NullPointerException("conn is null");
}
PreparedStatement ps = conn.prepareStatement("SELECT id,name,price,category,author,descs FROM tb_bookstore LIMIT ?,?");
if(ps==null){
throw new NullPointerException("ps is null");
}
ps.setInt(1, (page-1)*count);
ps.setInt(2, count);
ResultSet rs = ps.executeQuery();
if(rs==null){
throw new NullPointerException("rs is null");
}
List books = new ArrayList<>();
while (rs.next()) {
Book book = new Book();
book.setId(rs.getInt(1));
book.setName(rs.getString(2));
book.setPrice(rs.getDouble(3));
book.setCategory(rs.getString(4));
book.setAuthor(rs.getString(5));
book.setDescs(rs.getString(6));
books.add(book);
}
return books;
}
@Override
public int count() throws SQLException {
if(conn==null){
throw new NullPointerException("conn is null");
}
PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM tb_bookstore");
if(ps==null){
throw new NullPointerException("ps is null");
}
ResultSet rs = ps.executeQuery();
if(rs==null){
throw new NullPointerException("rs is null");
}
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
return count;
}
}
public interface BookService {
public Page findPage(int page,int count);
}
package com.yundoku.service.impl;
import java.sql.SQLException;
import java.util.List;
import com.yundoku.dao.BookDao;
import com.yundoku.dao.impl.BookDaoImpl;
import com.yundoku.domain.Book;
import com.yundoku.domain.Page;
import com.yundoku.service.BookService;
public class BookServiceImpl implements BookService{
private BookDao bookDao = new BookDaoImpl();
@Override
public Page findPage(int page, int count) {
if(bookDao==null){
bookDao = new BookDaoImpl();
}
try {
List books = bookDao.findBooks(page, count);
System.out.println(books);
int totle = bookDao.count();
System.out.println(totle);
Page p = new Page();
p.setBooks(books);
p.setCurrentPage(page);
p.setCount(count);
p.setTotalCount(totle);
int totlePage = totle%count==0?totle/count:(totle/count)+1;
p.setTotalPage(totlePage);
return p;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
public class Book {
private int id;
private String name;
private double price;
private String category;
private String author;
private String descs;
...
//省略get set方法
}
public class Page {
private int currentPage;//当前页
private int totalPage;//总页数
private int count;//一页多少条数据
private List books;//当前页的图书数据
private int totalCount;//数据总条数
...
//省略get set方法
}
@WebServlet({ "/HomeServlet", "/home" })
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HomeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
BookService service = new BookServiceImpl();
int currentPage=1;
int count=10;
String value = request.getParameter("page");
if(value!=null&&!"".equals(value)){
currentPage = Integer.parseInt(value);
}
Page page = service.findPage(currentPage, count);
request.setAttribute("page", page);
request.getRequestDispatcher("/jsp/home.jsp?page="+currentPage).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Insert title heretitle>
head>
<body>
<div align="center" >
<font size="5">
那些年一起追过的小说
font>
div>
<br/>
<table border="1" width="100%">
<tr>
<td>单号td>
<td>名称td>
<td>价格td>
<td>类别td>
<td>作者td>
<td>描述td>
tr>
<c:if test="${empty page.books }">
<tr>
<td colspan="8" align="center">没有商品td>
tr>
c:if>
<c:forEach items="${page.books }" var="book">
<tr>
<td>${book.id}td>
<td>${book.name}td>
<td>${book.price}td>
<td>${book.category}td>
<td>${book.author}td>
<td>${book.descs}td>
tr>
c:forEach>
table>
<br/>
<div align="center">
<c:if test="${page.currentPage>1 }">
<a href="${pageContext.request.contextPath }/home?page=${page.currentPage-1}">上一页a>
c:if>
<a href="${pageContext.request.contextPath }/home?page=${1}">首页a>
<c:forEach begin="1" end="${page.totalPage }" step="1" var="i">
<c:if test="${page.currentPage==i }">
<a href="${pageContext.request.contextPath }/home?page=${i}"><font color="#ff0000">${i}font>a>
c:if>
<c:if test="${page.currentPage!=i }">
<a href="${pageContext.request.contextPath }/home?page=${i}">${i}a>
c:if>
c:forEach>
<a href="${pageContext.request.contextPath }/home?page=${page.totalPage}">末页a>
<c:if test="${page.currentPage< page.totalPage }">
<a href="${pageContext.request.contextPath }/home?page=${page.currentPage+1}">下一页a>
c:if>
div>
body>
html>