您的位置:首页 > 其它

MyBatis分页插件PageHelper

2015-11-18 20:07 387 查看
分页实现步骤:共5步

1.在pom.xml中添加jar

<!-- 分页 -->

<dependency>

<groupId>com.github.pagehelper</groupId>

<artifactId>pagehelper</artifactId>

<version>3.6.0</version>

</dependency>

2.在applicationContext.xml中加入配置

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<!-- 自动扫描mapping.xml文件 -->

<property name="mapperLocations"

value="classpath:com/yiyang/luxuriesShop/mapping/*.xml"></property>

<!--分页插件-->

<property name="plugins">

<array>

<bean class="com.github.pagehelper.PageHelper">

<property name="properties">

<value>

dialect=mysql

reasonable=true

</value>

</property>

</bean>

</array>

</property>

</bean>

3.在ServiceImpl查询代码的前面加上一句话 "PageHelper.startPage(pageNum, pageSize);"

// 查看日志

@Override

public List<Cost> getLog(int pageNum, int pageSize) throws BaseException

{

List<Cost> list = null;

try

{

//分页辅助类

PageHelper.startPage(pageNum, pageSize);

list = getmapper().getLog();

}

catch (Exception e)

{

throw new DBException("数据异常,请联系管理员!");

}

return list;

}

4.在controller相关方法写上参数 将查询到的结果包装起来“ PageInfo<Cost> page = new PageInfo(list);”

// 消费记录

@SuppressWarnings("unchecked")

@RequestMapping(value = "history", method = RequestMethod.GET)

public String history(HttpServletRequest req) throws BaseException

{

List<Cost> list = null;

//获得页面传来的当前页参数

String str_pageNum = req.getParameter("pageNum");

//当前页默认为1,长度为2条记录

int pageNum = 1, pageSize = 2;

if (str_pageNum != null && isNum(str_pageNum))

{

pageNum = Integer.parseInt(str_pageNum);

}

try

{

list = vipService.getLog(pageNum, pageSize);

//将查询结果封装到pageInfo辅助类里面,这个类有分页相关的各种参数

@SuppressWarnings("rawtypes")

PageInfo<Cost> page = new PageInfo(list);

req.setAttribute("page", page);

}

catch (Exception e)

{

e.printStackTrace();

}

return "costHistory";

}

5.在jsp加上页码相关代码(如需带参数直接加到a标签pageNum后面即可)

<c:if test="${page.hasPreviousPage }">

<a class="left" href="${request.requireURL}?pageNum=${page.prePage}"><</a>

</c:if>

<c:forEach items="${page.navigatepageNums}" var="nav">

<c:if test="${nav == page.pageNum}">

<a href="#" class="cur"> ${nav} </a>

</c:if>

<c:if test="${nav != page.pageNum}">

<a href="${request.requireURL}?pageNum=${nav}>${nav}</a>

</c:if>

</c:forEach>

<c:if test="${page.hasNextPage}">

<a class="right" href="${request.requireURL}?pageNum=${page.nextPage}">>/a>

</c:if>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: