Mybatis-pagehelper一个非常好用的分页组件
- 在pom.xml文件下导入需要的包(在https://mvnrepository.com/ 搜索更多版本,个人使用4.2.0有报错,更改的4.1.6)
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
2.在spring配置文件下配置sqlsessionfactory
<!--创建sqlSession工厂对象 -->
<!--在此之前要保证mybatis的包和mybatis给spring提供的插件包都要导入到项目中 -->
<bean id="sessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据层查询文件(XxxMapper.xml文件)的地址 -->
<property name="mapperLocations"
value="classpath:com/lifei/shop/dao/*Mapper.xml" />
<!--将Spring创建的c3p0连接池对象 注入给工厂对象 -->
<property name="dataSource" ref="dataSource" />
<!-- 分页插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
这种方法,可以在mybatis全局配置文件下,添加监听器。
3.控制层使用
@RequestMapping("product-list.do")
@ResponseBody
public Result productList(@RequestParam(value="pageNum",defaultValue="1")int pageNum,
@RequestParam(value="pageSize",defaultValue="5")int pageSize){
PageHelper.startPage(pageNum,pageSize);
List<Product> proList = productService.list();
PageInfo<Product> pageInfo = new PageInfo<Product>(proList);
pageInfo.setList(proList);
Result result = new Result(pageInfo);
return result;
}
Result result = new Result(pageInfo);下封装了pageInfo
4.显示层
$.ajax({
url : "product-list.do",
type : "post",
data : {
"pageNum" : pageIndex(1),
"pageSize" : 5
},
dataType : "json",
success : function(result) {
/* alert(result.pageInfo.list[1].name); */
$(".datatr").remove();
for(var i=0;i<result.pageInfo.list.length;i++){
//组装html
var html='<tr class="datatr">';
html+='<td>'+result.pageInfo.list[i].pno+'</td>';
html+='<td>'+result.pageInfo.list[i].name+'</td>';
html+='<td><img src="'+result.pageInfo.list[i].image+'"></td>';
html+='<td>'+result.pageInfo.list[i].price+'</td>';
html+='<td>'+result.pageInfo.list[i].num+'</td>';
html+='<td><a class="addShopping" href="javascropt:" onclick="shopping('+result.pageInfo.list[i].pno+')">加入购物车</a></td>';
html+='</tr>';
//将html作为新的标签添加到最后一行之前
$("#last").before(html);
}
});
有疑问QQ:550611343