实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Brand implements Serializable {
private Integer id;
private String brandName;
private String companyName;
private Integer ordered;
private String description;
public Brand(String brandName, String companyName, Integer ordered, String description) {
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
}
private static final long serialVersionUID = 1L;
}
Mapper
@Select("select id, brand_name brandName, company_name companyName, ordered, description from tb_brand limit #{start},#{limit}")
public List<Brand> findAll(@Param("start") int start, @Param("limit") int limit);
Service
@Override
public List<Brand> findAll(int pageNum, int pageSize) {
int start = (pageNum - 1) * pageSize;
int limit = pageSize;
List<Brand> brands = mapper.findAll(start, limit);
sqlSession.clearCache();
return brands;
}
Servlet
@WebServlet("/BrandServlet")
public class BrandServlet extends HttpServlet {
private BrandService brandService = new BrandServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String num = req.getParameter("pageNum");
int pageNum = num == null ? 1 : Integer.parseInt(num);
int pageSize = 10;
List<Brand> brands = brandService.findAll(pageNum,pageSize);
int pageCount = brandService.getPageCount(pageSize);
System.err.println("brands.size(): " + brands.size());
req.setAttribute("brands", brands);
req.setAttribute("pageNum",pageNum);
req.setAttribute("pageCount",pageCount);
req.getRequestDispatcher("brand.jsp").forward(req, resp);
}
}
前端页面
<table>
<a href="addbrand.jsp">新增</a>
<tr>
<th>编号</th>
<th>品牌名称</th>
<th>公司名称</th>
<th>命令</th>
<th>描述</th>
<th>操作</th>
</tr>
<c:forEach var="brand" items="${brands}">
<tr>
<td>${brand.getId()}</td>
<td>${brand.getBrandName()}</td>
<td>${brand.getCompanyName()}</td>
<td>${brand.getOrdered()}</td>
<td>${brand.getDescription()}</td>
<td>
<a href="DeleteBrandServlet?id=${brand.getId()}">删除</a>
<a href="updatebrand.jsp?id=${brand.getId()}">修改</a>
</td>
</tr>
</c:forEach>
//主要是这下面
<tr>
<td colspan="9" align="center">
<c:if test="${pageNum==1}">
<label style="color: gray">首页</label>
<label style="color: gray">上一页</label>
</c:if>
<c:if test="${pageNum>1}">
<a href="BrandServlet?pageNum=1">首页</a>
<a href="BrandServlet?pageNum=${pageNum-1}">上一页</a>
</c:if>
当前页${pageNum}页/共${pageCount}页
<c:if test="${pageNum<pageCount}">
<a href="BrandServlet?pageNum=${pageNum+1}">下一页</a>
<a href="BrandServlet?pageNum=${pageCount}">尾页</a>
</c:if>
<c:if test="${pageNum==pageCount}">
<label style="color: gray">下一页</label>>
<label style="color: gray">尾页</label>>
</c:if>
</td>
</tr>
</table>