一,首先做一个查询所有并显示

dao

public interface ProductDAO {
	public List<Product> list();
}

mapper

<mapper namespace=\"hust.mm.dao.ProductDAO\">
	<select id=\"list\" resultType=\"Product\">
		select * from product
	</select>
</mapper>

controller

@RequestMapping(\"/list.do\")
public ModelAndView productlist(){
	ModelAndView mav = new ModelAndView();
		
	List<Product> products = productDao.list();
		
	mav.add (\"products\", products);
	mav.setViewName(\"productList\");
		
	return mav;
}

jsp

<table align=\"center\">
		<th>
			<td>id</td>
			<td>name</td>
			<td>price</td>
		</th>
		<c:forEach items=\"${products }\" var=\"p\" varStatus=\"st\">
			<tr>
				<td>${p.id }</td>
				<td>${p.name }</td>
				<td>${p.price }</td>
			</tr>
		</c:forEach>
</table>

以上简要给出了一个表中的所有数据

二,分页显示

修改dao

public interface ProductDAO {
	public List<Product> list();
	public List<Product> list(@Param(\"start\") int start, @Param(\"count\") int count);
}

修改mapper

<mapper namespace=\"hust.mm.dao.ProductDAO\">
    <select id=\"list\" resultType=\"Product\">
		select * from product
		<if test=\"start!=null and count!=null\">
			limit #{start},#{count}
		</if>
	</select>
</mapper>

修改controller

@RequestMapping(\"/list.do\")
public ModelAndView productlist(int start){
	ModelAndView mav = new ModelAndView();
		
	List<Product> products = productDao.list(start,3);
		
	mav.add (\"products\", products);
	mav.add (\"start\", start);
	mav.setViewName(\"productList\");
		
	return mav;
}

修改jsp

<table align=\"center\">
		<th>
			<td>id</td>
			<td>name</td>
			<td>price</td>
		</th>
		<c:forEach items=\"${products }\" var=\"p\" varStatus=\"st\">
			<tr>
				<td>${p.id }</td>
				<td>${p.name }</td>
				<td>${p.price }</td>
			</tr>
		</c:forEach>
        
        <tr>
			<td><a href=\"list.do?start=${start-3 }\">上一页</a></td>
			<td><a href=\"list.do?start=${start+3 }\">下一页</a></td>
		</tr>
</table>

这里以每页三条数据分页显示

三,完善分页

可以想到,当在首页点击上一页和在尾页点击下一页,应该没有反应或者做出相应处理。有两种解决方案,

  1. 使用jstl或el语句判断start参数是否小于0或大于total-分页大小
  2. 在controller对start进行判断

四,分页的其他方案

上述的分页是利用了mybatis的动态SQL以及MySQL数据库特有的limit语句。有一定的特殊性,可以使用PageHelper这一类分页插件来进行分页开发。

 

收藏 打印