`

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

 
阅读更多

参考资料 

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

2 UserController.java 

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

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


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.   
  6.    <resultMap type="com.liuzd.ssm.entity.User" id="userMap">  
  7.      <id property="id" column="id"/>  
  8.      <result property="name" column="name"/>  
  9.      <result property="age" column="age"/>  
  10.      <result property="sex" column="sex"/>  
  11.      <result property="address" column="address"/>  
  12.      <result property="password" column="password"/>         
  13.    </resultMap>    
  14.     <select id="pageList" parameterType="map" resultType="list" resultMap="userMap">     
  15.          
  16.        select ttt.* from(select tt.*,rownum rn from(select * from users  
  17.         <where>            
  18.            <if test="name != null and name != ''">  
  19.                <!--   
  20.                   特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。  
  21.                   在开发时使用: $,方便调试sql,发布时使用: #  
  22.                  and name like #{name},  
  23.                -->  
  24.                and name like '%${name}%'                     
  25.            </if>    
  26.             <if test="sex != null and sex != ''">  
  27.                and sex = #{sex}                      
  28.             </if>      
  29.          </where>    
  30.          order by ${orderName} ${descAsc} )tt)ttt  
  31.          <where>   
  32.            <if test="startIndex != null and startIndex != ''">  
  33.                rn > ${startIndex}                     
  34.            </if>    
  35.             <if test="endIndex != null and endIndex != ''">                
  36.                  <![CDATA[ and rn <= ${endIndex}  ]]>                               
  37.             </if>      
  38.          </where>            
  39. </select>    
  40.   
  41. <select id="pageCounts" parameterType="map" resultType="long">     
  42.    select count(*) from users   
  43.    <where>   
  44.    <if test="name != null and name != ''">  
  45.        and name like #{name}                     
  46.    </if>    
  47.     <if test="sex != null and sex != ''">  
  48.        and sex = #{sex}                      
  49.    </if>               
  50.    </where>    
  51. </select>   
  52.   
  53. </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.   
  31.                 <c:forEach items="${userList}" var="user">  
  32.                     <tr align="center">  
  33.                         <td>  
  34.                             ${user.name}  
  35.                         </td>  
  36.                         <td>  
  37.                             ${user.age}  
  38.                         </td>  
  39.                         <td>  
  40.                             ${user.sex eq 1 ? "男" : user.sex eq 2 ? "女" : "未知"}  
  41.                         </td>  
  42.                         <td>  
  43.                             ${user.address}  
  44.                         </td>  
  45.                         <td>  
  46.                             <a  
  47.                                 href="${pageContext.request.contextPath}/user/toAddUser.do">添加</a>  
  48.                             |  
  49.                             <a  
  50.                                 href="${pageContext.request.contextPath}/user/getUser/${user.id}.do">编辑</a>  
  51.                             |  
  52.                             <a  
  53.                                 href="${pageContext.request.contextPath}/user/delUser/${user.id}.do">删除</a>  
  54.                         </td>  
  55.                     </tr>  
  56.                 </c:forEach>  
  57.                 <jsp:include page="/page/page.jsp">  
  58.                     <jsp:param name="url" value="user/userList.do" />                   
  59.                 </jsp:include>  
  60.                   
  61.             </tbody>  
  62.         </table>  
  63.         <br>  
  64.         <a href="${pageContext.request.contextPath}/index.jsp">返回</a>         
  65.   </body>  
  66. </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}页&nbsp;  
  12.         <c:choose>  
  13.             <c:when test="${page.hasPrePage eq false}">  
  14.                 &lt&lt首页&nbsp;&lt上页&nbsp;  
  15.             </c:when>  
  16.             <c:otherwise>  
  17.                 <a href="${pathurl}?&pageAction=first${urlParams}">&lt&lt首页&nbsp;</a>&nbsp;  
  18.                 <a href="${pathurl}?pageAction=previous${urlParams}" />&lt上一页</a>  
  19.             </c:otherwise>  
  20.         </c:choose>  
  21.         &nbsp;||&nbsp;  
  22.         <c:choose>  
  23.             <c:when test="${page.hasNextPage eq false}">  
  24.                 &nbsp;下页&gt&nbsp;尾页&gt&gt  
  25.             </c:when>  
  26.             <c:otherwise>  
  27.                 <a href="${pathurl}?&pageAction=next${urlParams}">下一页&gt&nbsp;</a>&nbsp;  
  28.                 <a href="${pathurl}?pageAction=last${urlParams}" />末页&gt&gt</a>  
  29.             </c:otherwise>  
  30.         </c:choose>  
  31.         &nbsp;  
  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.         &nbsp;  
  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>  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics