本次分页的学习主要围绕用分页显示商品的信息,分页的代码编写基于空的购物车项目,使用到了老师自己编写封装的Pagination工具类及数据库连接DBConn类。
1.搭建分页显示商品信息的网页goods.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'goods.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<h1>显示商品信息</h1>
<div>
<table>
<tr>
<th>序号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>操作</th>
</tr>
<c:forEach var="g" items="${requestScope.pagination.rows }">
<tr>
<td>${g.id }</td>
<td>${g.name }</td>
<td>${g.price }</td>
<td>操作</td>
</tr>
</c:forEach>
<tr>
<td colspan="4"><a href="${pageContext.request.contextPath}/page1.do?nowpage=1">首页</a>
<a href="${pageContext.request.contextPath}/page1.do?nowpage=${pagination.nowPage-1}">上一页</a>
<a href="${pageContext.request.contextPath}/page1.do?nowpage=${pagination.nowPage+1}">下一页</a>
<a href="${pageContext.request.contextPath}/page1.do?nowpage=${pagination.pages}">末页</a></td>
</tr>
</table>
<div>项目路径:${pageContext.request.contextPath }</div>
</div>
</body>
</html>
2.新建一个Servlet : GoodsServletPage1.java (page1.do)
package blank.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 blank.dao.GoodsDao;
import blank.dao.impl.GoodsDaoImpl;
import blank.domain.Goods;
import blank.util.Pagination;
public class GoodsServletPage1 extends HttpServlet {
//数据库的操作对象
private GoodsDao goodsDao = new GoodsDaoImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取当前页
String npage = request.getParameter("nowpage");
//定义当前页的变量
int nowPage = 1;
//判断npage是否不等于null
if (npage!=null) {
//把String转换成int
nowPage = Integer.parseInt(npage);
}
//创建分页对象
Pagination<Goods> pagination = new Pagination<Goods>(3,nowPage,"goods");
//设置分页对象当前页的信息
pagination.setRows(goodsDao.getObjects(pagination.getStartSize(),pagination.getPageSize()));
//把分页对象存入到request域中
request.setAttribute("pagination", pagination);
//转发到goods.jsp
request.getRequestDispatcher("./goods.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
3.实现效果
附:使用到的数据库
版权声明:本文为博主原创文章,未经博主允许不得转载。