ITeye博客

SpringMVC3.0+MyIbatis3.0(分页示例)

a52071453 · 2013-10-30 17:24 · java · spring · mybatis/ibatis · 编程语言 · Markdown

参考资料

1 ibatis2.x与mybatis(ibatis3.x)的比较 
http://zhaohe162.blog.163.com/blog/static/382167972011111114742371/ 
2 MyBatis学习 之 三、动态SQL语句 
http://limingnihao.iteye.com/blog/782190 
主要使用Oracle的三层sql实现分页! 
一 环境:XP3+Oracle10g+MyEclipse6+(Tomcat)+JDK1.5 
二 工程相关图片: 
1 DEMO图片 

2 工程代码图片 
 
3 相关jar包图片 
 
三 此示例是在: 
SSI:SpringMVC3+Mybatis3(登录及CRUD操作)基础上加的分页功能: 
http://liuzidong.iteye.com/blog/1051760 
四 主要代码文件 
1 BaseController.java用于子类调用方便 

Java代码  收藏代码

  1. package com.liuzd.ssm.web;
  2. import javax.servlet.http.HttpServletRequest;
  3. import com.liuzd.page.Page;
  4. import com.liuzd.page.PageState;
  5. import com.liuzd.page.PageUtil;
  6. /**
  7. *Title:
  8. *Description:
  9. *Copyright: Copyright (c) 2011
  10. *Company:http://liuzidong.iteye.com/
  11. *Makedate:2011-5-23 下午03:31:03
  12. * @author liuzidong
  13. * @version 1.0
  14. * @since 1.0
  15. *
  16. */
  17. public class BaseController {
  18. /**
  19. * oracel的三层分页语句
  20. * 子类在展现数据前,进行分页计算!
  21. * @param totalCount 根据查询SQL获取的总条数
  22. * @param columnNameDescOrAsc 列名+排序方式 : ID DESC or ASC
  23. */
  24. protected Page executePage(HttpServletRequest request,Long totalCount){
  25. if(null == totalCount){
  26. totalCount = 0L;
  27. }
  28. /**页面状态,这个状态是分页自带的,与业务无关*/
  29. String pageAction = request.getParameter("pageAction");
  30. String value = request.getParameter("pageKey");
  31. /**获取下标判断分页状态*/
  32. int index = PageState.getOrdinal(pageAction);
  33. Page page = null;
  34. /**
  35. * index < 1 只有二种状态
  36. * 1 当首次调用时,分页状态类中没有值为 NULL 返回 -1
  37. * 2 当页面设置每页显示多少条: index=0,当每页显示多少条时,分页类要重新计算
  38. * */
  39. Page sessionPage = getPage(request);
  40. if(index < 1){
  41. page = PageUtil.inintPage(totalCount,index,value,sessionPage);
  42. }else{
  43. page = PageUtil.execPage(index,value,sessionPage);
  44. }
  45. setSession(request,page);
  46. return page;
  47. }
  48. private Page getPage(HttpServletRequest request) {
  49. Page page = (Page)request.getSession().getAttribute(PageUtil.SESSION_PAGE_KEY);
  50. if(page == null){
  51. page = new Page();
  52. }
  53. return page;
  54. }
  55. private void setSession(HttpServletRequest request,Page page) {
  56. request.getSession().setAttribute(PageUtil.SESSION_PAGE_KEY,page);
  57. }
  58. }

2 UserController.java 

Java代码  收藏代码

  1. package com.liuzd.ssm.web;
  2. import java.util.HashMap;
  3. import java.util.List;
  4. import java.util.Map;
  5. import javax.annotation.Resource;
  6. import javax.servlet.http.HttpServletRequest;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.SessionAttributes;
  11. import org.springframework.web.servlet.ModelAndView;
  12. import com.liuzd.page.Page;
  13. import com.liuzd.ssm.entity.User;
  14. import com.liuzd.ssm.service.UserService;
  15. @Controller
  16. @RequestMapping("/user")
  17. @SessionAttributes("userList")
  18. public class UserController extends BaseController{
  19. private UserService userService;
  20. public UserService getUserService() {
  21. return userService;
  22. }
  23. @Resource
  24. public void setUserService(UserService userService) {
  25. this.userService = userService;
  26. }
  27. @RequestMapping("/userList")
  28. public ModelAndView userList(HttpServletRequest request){
  29. Map<String,Object> params = new HashMap<String,Object>();
  30. //添加查询条件
  31. // ... params.put("name","jack");...
  32. //获取总条数
  33. Long totalCount = this.getUserService().pageCounts(params);
  34. //设置分页对象
  35. Page page = executePage(request,totalCount);
  36. //如排序
  37. if(page.isSort()){
  38. params.put("orderName",page.getSortName());
  39. params.put("descAsc",page.getSortState());
  40. }else{
  41. //没有进行排序,默认排序方式
  42. params.put("orderName","age");
  43. params.put("descAsc","asc");
  44. }
  45. //压入查询参数:开始条数与结束条灵敏
  46. params.put("startIndex", page.getBeginIndex());
  47. params.put("endIndex", page.getEndinIndex());
  48. ModelAndView mv = new ModelAndView();
  49. //查询集合
  50. List<User> users = this.getUserService().pageList(params);
  51. mv.addObject("userList",users);
  52. mv.setViewName("userList");
  53. return mv;
  54. }
  55. }

3 UserMapper.java 

Java代码  收藏代码

  1. package com.liuzd.ssm.mapper;
  2. import java.util.List;
  3. import java.util.Map;
  4. import org.apache.ibatis.session.RowBounds;
  5. import com.liuzd.ssm.entity.User;
  6. public interface UserMapper{
  7. // .....
  8. public List<User> pageList(Map<String,Object> params);
  9. //分页总条数
  10. public Long pageCounts(Map<String,Object> p);
  11. }

4 UserMapper.xml 

Java代码  收藏代码

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.liuzd.ssm.mapper.UserMapper">
  5. <resultMap type="com.liuzd.ssm.entity.User" id="userMap">
  6. <id property="id" column="id"/>
  7. <result property="name" column="name"/>
  8. <result property="age" column="age"/>
  9. <result property="sex" column="sex"/>
  10. <result property="address" column="address"/>
  11. <result property="password" column="password"/>
  12. </resultMap>
  13. <select id="pageList" parameterType="map" resultType="list" resultMap="userMap">
  14. select ttt.* from(select tt.*,rownum rn from(select * from users
  15. <where>
  16. <if test="name != null and name != ''">
  17. <!--
  18. 特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。
  19. 在开发时使用: $,方便调试sql,发布时使用: #
  20. and name like #{name},
  21. -->
  22. and name like '%${name}%'
  23. </if>
  24. <if test="sex != null and sex != ''">
  25. and sex = #{sex}
  26. </if>
  27. </where>
  28. order by ${orderName} ${descAsc} )tt)ttt
  29. <where>
  30. <if test="startIndex != null and startIndex != ''">
  31. rn > ${startIndex}
  32. </if>
  33. <if test="endIndex != null and endIndex != ''">
  34. <![CDATA[ and rn <= ${endIndex}  ]]>
  35. </if>
  36. </where>
  37. </select>
  38. <select id="pageCounts" parameterType="map" resultType="long">
  39. select count(*) from users
  40. <where>
  41. <if test="name != null and name != ''">
  42. and name like #{name}
  43. </if>
  44. <if test="sex != null and sex != ''">
  45. and sex = #{sex}
  46. </if>
  47. </where>
  48. </select>
  49. </mapper>

5 userList.jsp 

Java代码  收藏代码

  1. <%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
  2. <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  4. <html>
  5. <head>
  6. <%@ include file="/common/meta.jsp"%>
  7. </head>
  8. <body>
  9. <table width="60%" border="1" cellpadding="0" align="center">
  10. <thead>
  11. <tr>
  12. <th style="cursor: hand;" title="按姓名进行排序" onclick="sortPage('name')" valign="top">
  13. 姓名<font color='red'>${page.sortName eq "name" ? page.sortInfo : page.defaultInfo}</font>
  14. </th>
  15. <th style="cursor: hand;" title="按年龄进行排序" onclick="sortPage('age')" valign="top">
  16. 年龄<font color='red'>${page.sortName eq "age" ? page.sortInfo : page.defaultInfo}</font>
  17. </th>
  18. <th style="cursor: hand;" title="按性别进行排序" onclick="sortPage('sex')" valign="top">
  19. 性别<font color='red'>${page.sortName eq "sex" ? page.sortInfo : page.defaultInfo}</font>
  20. </th>
  21. <th style="cursor: hand;" title="按地址进行排序" onclick="sortPage('address')" valign="top">
  22. 地址<font color='red'>${page.sortName eq "address" ? page.sortInfo : page.defaultInfo}</font>
  23. </th>
  24. <th style="cursor: hand;" >
  25. 操作
  26. </th>
  27. </tr>
  28. </thead>
  29. <tbody>
  30. <c:forEach items="${userList}" var="user">
  31. <tr align="center">
  32. <td>
  33. ${user.name}
  34. </td>
  35. <td>
  36. ${user.age}
  37. </td>
  38. <td>
  39. ${user.sex eq 1 ? "男" : user.sex eq 2 ? "女" : "未知"}
  40. </td>
  41. <td>
  42. ${user.address}
  43. </td>
  44. <td>
  45. <a
  46. href="${pageContext.request.contextPath}/user/toAddUser.do">添加</a>
  47. |
  48. <a
  49. href="${pageContext.request.contextPath}/user/getUser/${user.id}.do">编辑</a>
  50. |
  51. <a
  52. href="${pageContext.request.contextPath}/user/delUser/${user.id}.do">删除</a>
  53. </td>
  54. </tr>
  55. </c:forEach>
  56. <jsp:include page="/page/page.jsp">
  57. <jsp:param name="url" value="user/userList.do" />
  58. </jsp:include>
  59. </tbody>
  60. </table>
  61. <br>
  62. <a href="${pageContext.request.contextPath}/index.jsp">返回</a>
  63. </body>
  64. </html>

6 page.jsp,此页面你不用关心,只管引用就行了 

Java代码  收藏代码

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
  2. <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
  3. <c:set var="page" value="${sessionScope.page}" />
  4. <c:set var="path" value="${pageContext.request.contextPath}" />
  5. <c:set var="url" value="${param.url}" />
  6. <c:set var="urlParams" value="${param.urlParams}" />
  7. <c:set var="pathurl" value="${path}/${url}" />
  8. <tr>
  9. <td colspan="5">
  10. 共${page.totalCount}条记录 共${page.totalPage}页 每页显示${page.everyPage}条
  11. 当前第${page.currentPage}页 
  12. <c:choose>
  13. <c:when test="${page.hasPrePage eq false}">
  14. &lt&lt首页 &lt上页 
  15. </c:when>
  16. <c:otherwise>
  17. <a href="${pathurl}?&pageAction=first${urlParams}">&lt&lt首页 </a> 
  18. <a href="${pathurl}?pageAction=previous${urlParams}" />&lt上一页</a>
  19. </c:otherwise>
  20. </c:choose>
  21.  || 
  22. <c:choose>
  23. <c:when test="${page.hasNextPage eq false}">
  24.  下页&gt 尾页&gt&gt
  25. </c:when>
  26. <c:otherwise>
  27. <a href="${pathurl}?&pageAction=next${urlParams}">下一页&gt </a> 
  28. <a href="${pathurl}?pageAction=last${urlParams}" />末页&gt&gt</a>
  29. </c:otherwise>
  30. </c:choose>
  31.  
  32. <SELECT name="indexChange" id="indexChange"
  33. onchange="getCurrentPage(this.value);">
  34. <c:forEach var="index" begin="1" end="${page.totalPage}" step="1">
  35. <option value="${index}" ${page.currentPage eq index ? "selected" : ""}>
  36. 第${index}页
  37. </option>
  38. </c:forEach>
  39. </SELECT>
  40.  
  41. 每页显示:<select name="everyPage" id="everyPage" onchange="setEveryPage(this.value);">
  42. <c:forEach var="pageCount" begin="5" end="${page.totalCount}" step="5">
  43. <option value="${pageCount}" ${page.everyPage eq pageCount ? "selected" : ""}>
  44. ${pageCount}条
  45. </option>
  46. </c:forEach>
  47. </select>
  48. </td>
  49. </tr>
  50. <div style='display: none'>
  51. <a class=listlink id="indexPageHref" href='#'></a>
  52. </div>
  53. <script>
  54. function getCurrentPage(index){
  55. var a = document.getElementById("indexPageHref");
  56. a.href = '${pathurl}?pageAction=gopage&pageKey='+index+'${urlParams}';
  57. a.setAttribute("onclick",'');
  58. a.click("return false");
  59. }
  60. function setEveryPage(everyPage){
  61. var a = document.getElementById("indexPageHref");
  62. var currentPage = document.getElementById('indexChange').value;
  63. a.href = '${pathurl}?pageAction=setpage&pageKey='+everyPage+'${urlParams}';
  64. a.setAttribute("onclick",'');
  65. a.click("return false");
  66. }
  67. function sortPage(sortName){
  68. var a = document.getElementById("indexPageHref");
  69. a.href = '${pathurl}?pageAction=sort&pageKey='+sortName+'${urlParams}';
  70. a.setAttribute("onclick",'');
  71. a.click("return false");
  72. }
  73. </script>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。