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图片
SpringMVC3.0+MyIbatis3.0(分页示例)_第1张图片
2 工程代码图片
SpringMVC3.0+MyIbatis3.0(分页示例)_第2张图片
3 相关jar包图片
SpringMVC3.0+MyIbatis3.0(分页示例)_第3张图片
三 此示例是在:
SSI:SpringMVC3+Mybatis3(登录及CRUD操作)基础上加的分页功能:
http://liuzidong.iteye.com/blog/1051760
四 主要代码文件
1 BaseController.java用于子类调用方便
package com.liuzd.ssm.web;

import javax.servlet.http.HttpServletRequest;

import com.liuzd.page.Page;
import com.liuzd.page.PageState;
import com.liuzd.page.PageUtil;

/**   
 *Title:     
 *Description:     
 *Copyright: Copyright (c) 2011   
 *Company:http://liuzidong.iteye.com/    
 *Makedate:2011-5-23 下午03:31:03   
 * @author liuzidong   
 * @version 1.0   
 * @since 1.0    
 *   
 */
public class BaseController {
	
	/**
	 * oracel的三层分页语句	
	 * 子类在展现数据前,进行分页计算!	
	 * @param totalCount 根据查询SQL获取的总条数
	 * @param columnNameDescOrAsc 列名+排序方式 : ID DESC or ASC
	 */
	protected Page executePage(HttpServletRequest request,Long totalCount){
		if(null == totalCount){
			totalCount = 0L;
		}
		/**页面状态,这个状态是分页自带的,与业务无关*/
		String pageAction = request.getParameter("pageAction");
		String value = request.getParameter("pageKey");
		
		/**获取下标判断分页状态*/
		int index = PageState.getOrdinal(pageAction);				
		
		Page page = null;		
		/**
		 * index < 1 只有二种状态
		 * 1 当首次调用时,分页状态类中没有值为 NULL 返回 -1
		 * 2 当页面设置每页显示多少条: index=0,当每页显示多少条时,分页类要重新计算
		 * */
		Page sessionPage = getPage(request);
		
		if(index < 1){			
			page = PageUtil.inintPage(totalCount,index,value,sessionPage);
		}else{				
			page = PageUtil.execPage(index,value,sessionPage);
		}		
		setSession(request,page);	
		return page;
	}	
	
	private Page getPage(HttpServletRequest request) {
		Page page = (Page)request.getSession().getAttribute(PageUtil.SESSION_PAGE_KEY);
		if(page == null){
			page = new Page();
		}
		return page;		
	}	
	
	private void setSession(HttpServletRequest request,Page page) {
		request.getSession().setAttribute(PageUtil.SESSION_PAGE_KEY,page);		
	}	

}

2 UserController.java

package com.liuzd.ssm.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.liuzd.page.Page;
import com.liuzd.ssm.entity.User;
import com.liuzd.ssm.service.UserService;

@Controller
@RequestMapping("/user")
@SessionAttributes("userList")
public class UserController extends BaseController{
	
	private UserService userService;
	

	public UserService getUserService() {
		return userService;
	}
	
	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}	

	
	@RequestMapping("/userList")
	public ModelAndView userList(HttpServletRequest request){
		Map<String,Object> params = new HashMap<String,Object>();
		//添加查询条件
		// ... params.put("name","jack");...
		
		//获取总条数
		Long totalCount = this.getUserService().pageCounts(params);
		//设置分页对象
		Page page = executePage(request,totalCount);		
		//如排序
		if(page.isSort()){
			params.put("orderName",page.getSortName());	
			params.put("descAsc",page.getSortState());
		}else{
			//没有进行排序,默认排序方式
			params.put("orderName","age");	
			params.put("descAsc","asc");
		}
		//压入查询参数:开始条数与结束条灵敏
		params.put("startIndex", page.getBeginIndex());
		params.put("endIndex", page.getEndinIndex());
		
		ModelAndView mv = new ModelAndView();		
		//查询集合		
		List<User> users = this.getUserService().pageList(params);
		mv.addObject("userList",users);				
		mv.setViewName("userList");			
		return mv;
	}
}	

3 UserMapper.java
package com.liuzd.ssm.mapper;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;

import com.liuzd.ssm.entity.User;

public interface UserMapper{
	
	// .....	
	public List<User> pageList(Map<String,Object> params);
	//分页总条数
	public Long pageCounts(Map<String,Object> p);
	
}


4 UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liuzd.ssm.mapper.UserMapper">  	

   <resultMap type="com.liuzd.ssm.entity.User" id="userMap">
   	 <id property="id" column="id"/>
   	 <result property="name" column="name"/>
   	 <result property="age" column="age"/>
   	 <result property="sex" column="sex"/>
   	 <result property="address" column="address"/>
   	 <result property="password" column="password"/>   	 
   </resultMap>  
    <select id="pageList" parameterType="map" resultType="list" resultMap="userMap">   
       
       select ttt.* from(select tt.*,rownum rn from(select * from users
    	<where>     	   
		   <if test="name != null and name != ''">
		       <!-- 
		          特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。
		          在开发时使用: $,方便调试sql,发布时使用: #
		         and name like #{name},
		       -->
		       and name like '%${name}%' 				   
		   </if>	
		   	<if test="sex != null and sex != ''">
		       and sex = #{sex}  				   
		    </if>    
		 </where>  
		 order by ${orderName} ${descAsc} )tt)ttt
		 <where> 
		   <if test="startIndex != null and startIndex != ''">
		       rn > ${startIndex}  				   
		   </if>	
		   	<if test="endIndex != null and endIndex != ''">		   	   
		         <![CDATA[ and rn <= ${endIndex}  ]]> 			        		   
		    </if>    
		 </where>		 	 
</select>  

<select id="pageCounts" parameterType="map" resultType="long">   
   select count(*) from users 
   <where> 
   <if test="name != null and name != ''">
       and name like #{name}  				   
   </if>	
   	<if test="sex != null and sex != ''">
       and sex = #{sex}  				   
   </if>		       
   </where>  
</select> 

</mapper>

5 userList.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <%@ include file="/common/meta.jsp"%>
  </head>  
  <body>
      <table width="60%" border="1" cellpadding="0" align="center">
			<thead>
				<tr>
					<th style="cursor: hand;" title="按姓名进行排序" onclick="sortPage('name')" valign="top">
						姓名<font color='red'>${page.sortName eq "name" ? page.sortInfo : page.defaultInfo}</font>
					</th>
					<th style="cursor: hand;" title="按年龄进行排序" onclick="sortPage('age')" valign="top">
						年龄<font color='red'>${page.sortName eq "age" ? page.sortInfo : page.defaultInfo}</font>
					</th>
					<th style="cursor: hand;" title="按性别进行排序" onclick="sortPage('sex')" valign="top">
						性别<font color='red'>${page.sortName eq "sex" ? page.sortInfo : page.defaultInfo}</font>
					</th>
					<th style="cursor: hand;" title="按地址进行排序" onclick="sortPage('address')" valign="top">
						地址<font color='red'>${page.sortName eq "address" ? page.sortInfo : page.defaultInfo}</font>
					</th>
					<th style="cursor: hand;" >
						操作
					</th>
				</tr>
			</thead>
			<tbody>			

				<c:forEach items="${userList}" var="user">
					<tr align="center">
						<td>
							${user.name}
						</td>
						<td>
							${user.age}
						</td>
						<td>
							${user.sex eq 1 ? "男" : user.sex eq 2 ? "女" : "未知"}
						</td>
						<td>
							${user.address}
						</td>
						<td>
							<a
								href="${pageContext.request.contextPath}/user/toAddUser.do">添加</a>
							|
							<a
								href="${pageContext.request.contextPath}/user/getUser/${user.id}.do">编辑</a>
							|
							<a
								href="${pageContext.request.contextPath}/user/delUser/${user.id}.do">删除</a>
						</td>
					</tr>
				</c:forEach>
				<jsp:include page="/page/page.jsp">
					<jsp:param name="url" value="user/userList.do" />					
				</jsp:include>
				
			</tbody>
		</table>
		<br>
		<a href="${pageContext.request.contextPath}/index.jsp">返回</a>		
  </body>
</html>

6 page.jsp,此页面你不用关心,只管引用就行了
<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
<c:set var="page" value="${sessionScope.page}" />
<c:set var="path" value="${pageContext.request.contextPath}" />
<c:set var="url" value="${param.url}" />
<c:set var="urlParams" value="${param.urlParams}" />
<c:set var="pathurl" value="${path}/${url}" />
<tr>
	<td colspan="5">
		共${page.totalCount}条记录 共${page.totalPage}页 每页显示${page.everyPage}条
		当前第${page.currentPage}页&nbsp;
		<c:choose>
			<c:when test="${page.hasPrePage eq false}">
 			    &lt&lt首页&nbsp;&lt上页&nbsp;
 			</c:when>
			<c:otherwise>
				<a href="${pathurl}?&pageAction=first${urlParams}">&lt&lt首页&nbsp;</a>&nbsp;
				<a href="${pathurl}?pageAction=previous${urlParams}" />&lt上一页</a>
			</c:otherwise>
		</c:choose>
		&nbsp;||&nbsp;
		<c:choose>
			<c:when test="${page.hasNextPage eq false}">
 			    &nbsp;下页&gt&nbsp;尾页&gt&gt
 			</c:when>
			<c:otherwise>
				<a href="${pathurl}?&pageAction=next${urlParams}">下一页&gt&nbsp;</a>&nbsp;
				<a href="${pathurl}?pageAction=last${urlParams}" />末页&gt&gt</a>
			</c:otherwise>
		</c:choose>
		&nbsp;
		<SELECT name="indexChange" id="indexChange"
			onchange="getCurrentPage(this.value);">
			<c:forEach var="index" begin="1" end="${page.totalPage}" step="1">
				<option value="${index}" ${page.currentPage eq index ? "selected" : ""}>
					第${index}页
				</option>
			</c:forEach>
		</SELECT>
		&nbsp;
		每页显示:<select name="everyPage" id="everyPage" onchange="setEveryPage(this.value);">
			       <c:forEach var="pageCount" begin="5" end="${page.totalCount}" step="5">			       	    
						<option value="${pageCount}" ${page.everyPage eq pageCount ? "selected" : ""}>
							${pageCount}条
						</option>
					</c:forEach>
		       </select>
	</td>
</tr>
<div style='display: none'>
	<a class=listlink id="indexPageHref" href='#'></a>
</div>
<script>
function getCurrentPage(index){	
	var a = document.getElementById("indexPageHref");	
	a.href = '${pathurl}?pageAction=gopage&pageKey='+index+'${urlParams}';        
    a.setAttribute("onclick",'');          
    a.click("return false");   
}
function setEveryPage(everyPage){	
	var a = document.getElementById("indexPageHref");
	var currentPage = document.getElementById('indexChange').value;
	a.href = '${pathurl}?pageAction=setpage&pageKey='+everyPage+'${urlParams}';       
    a.setAttribute("onclick",'');          
    a.click("return false");   
}
function sortPage(sortName){	
	var a = document.getElementById("indexPageHref");	
	a.href = '${pathurl}?pageAction=sort&pageKey='+sortName+'${urlParams}';      
    a.setAttribute("onclick",'');      
    a.click("return false");   
}
</script>

你可能感兴趣的:(sql,jsp,Web,ibatis,ITeye)