分页的实现

1.首页

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
<style type="text/css">
	a{
	text-decoration: none;
}
</style>
</head>
<body>
	<table border="1" width="40%" class="imagetable" align="center">
		<tr>
			<td align="center"><a href="${pageContext.request.contextPath }/searchAll?pageNumber=1">点击查询所有商品</a></td>
		</tr>
	</table>
	<hr/>
</body>
</html>


2.查询页

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <!-- 导入jstl标签 -->
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
<style type="text/css">
a{
	text-decoration: none;
}
</style>
</head>
<body>
	<table border="1" width="40%" class="imagetable" align="center">
		<tr>
			<th>商品列表</th>
		</tr>
	</table>
	<hr/>
	<table border="1" width="100%" class="imagetable">
		<tr>
			<th colspan="5" align="right">
				<input type="button" value="添加商品"/>
			</th>
		</tr>
		<tr>
			<th>商品序号</th>
			<th>商品名称</th>
			<th>商品图片</th>
			<th>商品价格</th>
			<th>商品描述</th>
		</tr>
		<c:if test="${not empty pageBean.list }">
		<!-- 循环得到plist中的需要的数据                 varstatus 是记录循环状态信息的 -->
			<c:forEach items="${pageBean.list }" var="c" varStatus="con">
				<tr>
					<td>${con.count }</td>
					<td>${c.pname }</td>
					<td><img src="${c.pimage }"  width="100%"></td>
					<td>${c.shop_price }</td>
					<td>${c.pdesc }</td>
				</tr>
			</c:forEach>
		</c:if>
		<tr>
			<th colspan="5" align="center">
			<!--上一页  -->
			<!-- 第一页不可点击 -->
			<c:choose>
				<c:when test="${pageBean.pageNumber==1}">
					<a>上一页</a>
				</c:when>
				<c:otherwise>
					<a href="${pageContext.request.contextPath }/searchAll?pageNumber=${pageBean.pageNumber-1}">上一页</a>
				</c:otherwise>
			</c:choose>
			
			
			<!-- 显示页数 -->
			<!-- 当前页不可点击 -->
				<c:forEach begin="1" end="${pageBean.totalPage }" var="pg">
						<c:if test="${pg!=pageBean.pageNumber}">
							<a href="${pageContext.request.contextPath }/searchAll?pageNumber=${pg}">${pg }</a>
						</c:if>
						<c:if test="${pg==pageBean.pageNumber}">
							<a>${pg }</a>
						</c:if>
				</c:forEach>
			
			<!-- 下一页 -->
			<!-- 最后一页不可点击 -->
			<c:choose>
				<c:when test="${pageBean.pageNumber==pageBean.totalPage}">
					<a>下一页</a>
				</c:when>
				<c:otherwise>
					<a href="${pageContext.request.contextPath }/searchAll?pageNumber=${pageBean.pageNumber+1}">下一页</a>
				</c:otherwise>
			</c:choose>
			</th>
		</tr>
	</table>
</body>
</html>


3.工具类

package yynh.com.store.product.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3p0Utils {

	// 连接池就定义 并且加载配置完毕
	// 命名配置
	// private static DataSource dataSource=new ComboPooledDataSource("itcast");

	// 默认配置
	private static DataSource dataSource = new ComboPooledDataSource();

	// c3p0+DBUtils
	// DBUtils使用时,需要获取dataSource对象
	public static DataSource getDataSource() {
		return dataSource;
	}

	/**
	 * 获取链接方法
	 */
	public static Connection getConnection() {
		Connection con = null;
		try {
			con = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return con;
	}

	public static void main(String[] args) throws SQLException {
		for (int i = 0; i < 40; i++) {
			Connection con = C3p0Utils.getConnection();
			System.out.println("获取到的" + con);
			// 不会关闭con对象,C3P0已经帮我去增强了Connection close方法
			con.close();

		}
	}
}


4.javaBean


package yynh.com.store.product.domain;

import java.io.Serializable;

public class Category implements Serializable {
	private String cid;
	private String cname;

	public String getCid() {
		return cid;
	}

	public void setCid(String cid) {
		this.cid = cid;
	}

	public String getCname() {
		return cname;
	}

	public void setCname(String cname) {
		this.cname = cname;
	}

	public Category() {
		super();
		// TODO Auto-generated constructor stub
	}

}
package yynh.com.store.product.domain;

import java.io.Serializable;
import java.util.List;

public class PageBean<T> implements Serializable {
	private int pageNumber;
	private int beginIndex;
	private int pageSize;
	private int totalRecord;
	private int totalPage;
	private List<T> list;

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public int getBeginIndex() {
		// 计算出开始索引
		return (this.getPageNumber() - 1) * this.getPageSize();
	}

	public void setBeginIndex(int beginIndex) {
		this.beginIndex = beginIndex;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalRecord() {
		return totalRecord;
	}

	public void setTotalRecord(int totalRecord) {
		this.totalRecord = totalRecord;
	}

	// 计算出总页数
	public int getTotalPage() {
		return (this.getTotalRecord() % this.getPageSize() == 0) ? this.getTotalRecord() / this.getPageSize() : this.getTotalRecord() / this.getPageSize() + 1;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public List<T> getList() {
		return list;
	}

	public void setList(List<T> list) {
		this.list = list;
	}

	public PageBean() {
		super();
		// TODO Auto-generated constructor stub
	}

}

package yynh.com.store.product.domain;

import java.io.Serializable;
import java.util.Date;

public class Product implements Serializable {
	private String pid;
	private String pname;
	private double shop_price;
	private String pimage;
	private Date pdate;
	private String pdesc;
	// 创建外键约束
	private Category category;

	public String getPid() {
		return pid;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	public String getPname() {
		return pname;
	}

	public void setPname(String pname) {
		this.pname = pname;
	}

	public double getShop_price() {
		return shop_price;
	}

	public void setShop_price(double shop_price) {
		this.shop_price = shop_price;
	}

	public String getPimage() {
		return pimage;
	}

	public void setPimage(String pimage) {
		this.pimage = pimage;
	}

	public Date getPdate() {
		return pdate;
	}

	public void setPdate(Date pdate) {
		this.pdate = pdate;
	}

	public String getPdesc() {
		return pdesc;
	}

	public void setPdesc(String pdesc) {
		this.pdesc = pdesc;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public Product() {
		super();
		// TODO Auto-generated constructor stub
	}

}



5.servlet

package yynh.com.store.product.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import yynh.com.store.product.domain.PageBean;
import yynh.com.store.product.domain.Product;
import yynh.com.store.product.service.ProductService;
import yynh.com.store.product.service.ProductServiceIml;

/**
 * Servlet implementation class SearchAll
 */
public class SearchAll extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 查询所有商品
			// 获取参数
			Integer pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
			PageBean<Product> pageBean = new PageBean<Product>();
			pageBean.setPageNumber(pageNumber);
			// 调用service
			ProductService service = new ProductServiceIml();
			// List<Product> plist = service.searchAll();
			pageBean = service.search(pageBean);
			// 回显数据
			request.setAttribute("pageBean", pageBean);

			request.getRequestDispatcher("/plist.jsp").forward(request, response);
		} catch (Exception e) {
			// 出现异常时,向浏览器显示
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print("查询出错了哦");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


6.service

package yynh.com.store.product.service;

import java.util.List;

import yynh.com.store.product.dao.ProductDao;
import yynh.com.store.product.dao.ProductDaoIml;
import yynh.com.store.product.domain.PageBean;
import yynh.com.store.product.domain.Product;

public class ProductServiceIml implements ProductService {
	ProductDao pd = new ProductDaoIml();

	/**
	 * 商品分页信息 第三版
	 */
	@Override
	public PageBean<Product> search(PageBean<Product> pageBean) {
		// 设置每页显示的记录数
		int pageSize = 10;
		pageBean.setPageSize(pageSize);
		// 获取总记录数
		int totalRecord = pd.count();
		pageBean.setTotalRecord(totalRecord);
		// 分页查询
		List<Product> list = pd.search(pageBean);
		pageBean.setList(list);
		return pageBean;

	}

	/**
	 * 分页查询商品信息 第二版
	 */
	/*
	 * public PageBean search(PageBean pageBean) { // 1.设置每页显示的数据 int pageSize = 10; pageBean.setPageSize(pageSize); // 2.获取总记录数 int totalRecord = pd.count(); pageBean.setTotalRecord(totalRecord); // 3.计算出开始索引 用pagebean调用,更加严谨 int beginIndex = (pageBean.getPageNumber() - 1) * pageBean.getPageSize(); pageBean.setBeginIndex(beginIndex); // 4.计算出总页数 // totalRecord/pageSize 得出的值由于没有指定doble类型, 所以默认是int类型,会将小数点之后的数据遗弃 int totalPage = (pageBean.getTotalRecord() % pageBean.getPageSize() == 0) ? pageBean.getTotalRecord() / pageBean.getPageSize() : pageBean.getTotalRecord() / pageBean.getPageSize() + 1; pageBean.setTotalPage(totalPage); // 5.调用dao返回分页查询的记录 List<Product> list = pd.search(pageBean); pageBean.setList(list); return pageBean; }
	 */
	/**
	 * 分页查询商品信息
	 */
	/*
	 * public List<Product> search(Integer pageNumber) { // 获取数据的总数 int totalRecord = pd.count(); // 设置每页展示的记录 int pageSize = 10; // 计算出开始索引 int totalPage = (totalRecord % pageSize == 0) ? totalRecord / pageSize : totalRecord % pageSize + 1;
	 * 
	 * // 调用查询方法 List<Product> plist = pd.search(totalPage, pageSize); return plist; }
	 */
	/*	*//**
			 * 查询所有商品信息
			 *//*
			 * public List<Product> searchAll() {
			 * 
			 * List<Product> plist = pd.searchAll(); return plist; }
			 */
}


7.dao


package yynh.com.store.product.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import yynh.com.store.product.domain.PageBean;
import yynh.com.store.product.domain.Product;
import yynh.com.store.product.utils.C3p0Utils;

public class ProductDaoIml implements ProductDao {
	/**
	 * 查询所有商品条目数量
	 */
	@Override
	public int count() {
		Long result = new Long(0);
		QueryRunner run = new QueryRunner(C3p0Utils.getDataSource());
		String sql = "select count(*) from product";
		try {
			// 由于只需要单行单列的数据,所以用scalarhandler 由于它的值不能直接赋值int,所以用long代替
			result = (Long) run.query(sql, new ScalarHandler());
		} catch (SQLException e) {
			e.printStackTrace();
			// 抛出异常
			throw new RuntimeException();
		}
		// 强转成int
		return result.intValue();
	}

	/**
	 * 查询分页商品信息
	 */
	@Override
	public List<Product> search(PageBean<Product> pageBean) {
		// 创建dbutils的核心类对象
		QueryRunner run = new QueryRunner(C3p0Utils.getDataSource());
		String sql = "select * from product order by pdate desc limit ?,?";
		Object[] param = { pageBean.getBeginIndex(), pageBean.getPageSize() };
		try {
			List<Product> plist = run.query(sql, new BeanListHandler<Product>(Product.class), param);
			return plist;
		} catch (SQLException e) {
			e.printStackTrace();
			// 抛出异常
			throw new RuntimeException();
		}
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值