springMvc +Jdbctemplate+分頁
--------spring jdbcTemplate mysql oracle 分頁工具類
public class Pagination extends JdbcDaoSupport{
public static final int NUMBERS_PER_PAGE = 10;
//一頁顯示的記錄數
private int numPerPage;
//記錄總數
private int totalRows;
//總頁數
private int totalPages;
//當前頁碼
//起始行數
private int startIndex;
//結束行數
private int lastIndex;
//結果集存放List
private List resultList;
//JdbcTemplate jTemplate
private JdbcTemplate jTemplate;
/**
* 每頁顯示10條記錄的建構函式,使用該函式必須先給Pagination設定currentPage,jTemplate初值
*/
public Pagination(String sql){
if(jTemplate == null){
throw new IllegalArgumentException("com.deity.ranking.util.Pagination.jTemplate is null,please initial it first. ");
}else if(sql.equals("")){
}
new Pagination(sql,currentPage,NUMBERS_PER_PAGE,jTemplate);
}
/**分頁建構函式
* @param sql 根據傳入的sql語句得到一些基本分頁資訊
* @param currentPage 當前頁
* @param numPerPage 每頁記錄數
* @param jTemplate JdbcTemplate例項
*/
public Pagination(String sql,int currentPage,int numPerPage,JdbcTemplate jTemplate){
if(jTemplate == null){
throw new IllegalArgumentException("com.deity.ranking.util.Pagination.jTemplate is null,please initial it first. ");
}else if(sql == null || sql.equals("")){
throw new IllegalArgumentException("com.deity.ranking.util.Pagination.sql is empty,please initial it first. ");
}
//設定每頁顯示記錄數
setNumPerPage(numPerPage);
//設定要顯示的頁數
setCurrentPage(currentPage);
//計算總記錄數
StringBuffer totalSQL = new StringBuffer(" SELECT count(*) FROM ( ");
totalSQL.append(sql);
totalSQL.append(" ) totalTable ");
//給JdbcTemplate賦值
setJdbcTemplate(jTemplate);
//總記錄數
setTotalRows(getJdbcTemplate().queryForInt(totalSQL.toString()));
//計算總頁數
setTotalPages();
//計算起始行數
setStartIndex();
//計算結束行數
setLastIndex();
system.out.println("lastIndex="+lastIndex);//////////////////
//構造oracle資料庫的分頁語句
/** StringBuffer paginationSQL = new StringBuffer(" SELECT * FROM ( ");
paginationSQL.append(" SELECT temp.* ,ROWNUM num FROM ( ");
paginationSQL.append(sql);
paginationSQL.append(" ) temp where ROWNUM <= " + lastIndex);
paginationSQL.append(" ) WHERE num > " + startIndex);
*/
//裝入結果集
setResultList(getJdbcTemplate().queryForList(getMySQLPageSQL(sql,startIndex,numPerPage)));
}
/**
* 構造MySQL資料分頁SQL
* @param queryString
* @param startIndex
* @param pageSize
* @return
*/
public String getMySQLPageSQL(String queryString, Integer startIndex, Integer pageSize)
{
String result = "";
if (null != startIndex && null != pageSize)
{
result = queryString + " limit " + startIndex + "," + pageSize;
} else if (null != startIndex && null == pageSize)
{
result = queryString + " limit " + startIndex;
} else
{
result = queryString;
}
return result;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getNumPerPage() {
return numPerPage;
}
public void setNumPerPage(int numPerPage) {
this.numPerPage = numPerPage;
}
public List getResultList() {
return resultList;
}
public void setResultList(List resultList) {
this.resultList = resultList;
}
public int getTotalPages() {
return totalPages;
}
//計算總頁數
public void setTotalPages() {
if(totalRows % numPerPage == 0){
this.totalPages = totalRows / numPerPage;
}else{
this.totalPages = (totalRows / numPerPage) + 1;
}
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex() {
this.startIndex = (currentPage - 1) * numPerPage;
}
public int getLastIndex() {
return lastIndex;
}
public JdbcTemplate getJTemplate() {
return jTemplate;
}
public void setJTemplate(JdbcTemplate template) {
jTemplate = template;
}
//計算結束時候的索引
public void setLastIndex() {
System.out.println("totalRows="+totalRows);///////////
System.out.println("numPerPage="+numPerPage);///////////
if( totalRows < numPerPage){
this.lastIndex = totalRows;
}else if((totalRows % numPerPage == 0) || (totalRows % numPerPage != 0 && currentPage < totalPages)){
this.lastIndex = currentPage * numPerPage;
}else if(totalRows % numPerPage != 0 && currentPage == totalPages){//最後一頁
this.lastIndex = totalRows ;
}
}
}
/**
* 業務處理
* @author Administrator
*
*/
@Service("BusinessService")
public class BusinessService {
@Resource
private BusinessDao businessDao;
/**
* 分頁查詢
* @param currentPage 當前頁
* @param numPerPage 每頁記錄數
* @return
*/
public Pagination queryPageBusiness(Integer currentPage,Integer numPerPage) {
return businessDao.queryPageBusiness(currentPage, numPerPage);
}
}
@Controller
@RequestMapping(value = http://blog.csdn.net/huahuagongzi9999/article/details/"/business")
public class BusinessController {
@Resource
private BusinessService businessService;
private final static String uploadURL=propertiesUtil.getUrl("uploadURL");
/**
* 分頁查詢所有
* @param request
* @param response
*/
@RequestMapping(value = "queryPageBusiness.do")
public void queryPageBusiness(HttpServletRequest request,HttpServletResponse response) {
String message = "";
String status = "";
PrintWriter out = null;
List<Map<String, Object>> businessList =null;
Pagination page=null;
Map<String, Object> map = new HashMap<String, Object>();
try {
out = response.getWriter();
String currentPage = URLDecoder.decode(request.getParameter("currentPage"));
String numPerPage = URLDecoder.decode(request.getParameter("numPerPage"));
if("".equals(currentPage)||"".equals(numPerPage)){
page =businessService.queryPageBusiness(1, 10);
}else{
page =businessService.queryPageBusiness(StringUtil.getInteger(currentPage), StringUtil.getInteger(numPerPage));
}
List list=page.getResultList();
businessList=new ArrayList<Map<String,Object>>();
for (int i = 0,len=list.size();i<len; i++) {
Map<String, Object> maps=new HashMap<String, Object>();
Map mapRe=(Map)list.get(i);
maps.put("businessPic", StringUtil.nullOrBlank(mapRe.get("businessPic")+"")?"?"":uploadURL+mapRe.get("businessPic"));
maps.put("businessName", mapRe.get("businessName"));
maps.put("businessId", mapRe.get("businessId"));
maps.put("businessEname", mapRe.get("businessEname"));
maps.put("createTime", FormatDateTime.formatDateTime("yyyy-MM-dd", mapRe.get("createTime")+""));
businessList.add(maps);
}
message="success";
status = Constants.RETURN_STATUS_0;
} catch (Exception e1) {
e1.printStackTrace();
message="failure";
status = Constants.RETURN_STATUS_1;
}finally{
map.put("message", message);
map.put("totalPage", page.getTotalPages());
map.put("currentPage", page.getCurrentPage());
map.put("totalRows", page.getTotalRows());
map.put("numPerPage", page.getNumPerPage());
map.put("status", status);
map.put("businessList", businessList);
//必須設定字元編碼,否則返回json會亂碼
response.setContentType("text/html;charset=UTF-8");
out.write(JSONSerializer.toJSON(map).toString());
out.flush();
out.close();
}
}
}
@Repository("businessDao")
public class BusinessDao extends AbstractDao{
/**
* 分頁查詢
* @param currentPage 當前頁
* @param numPerPage 每頁記錄數
* @return
*/
public Pagination queryPageBusiness(Integer currentPage,Integer numPerPage) {
String sql="SELECT * FROM business ORDER BY businessId ASC ";
Pagination page=new Pagination(sql, currentPage, numPerPage, getJdbcTemplate());
return page;
}
}
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="ctx" value="${pageContext.request.contextPath }" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>分頁列表</title>
<link href="${ctx}/bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="${ctx}/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">
<link rel="stylesheet" href="${ctx}/css/bootstrap-responsive.min.css" />
<link rel="stylesheet" href="${ctx}/css/jquery-ui.css" />
<link rel="stylesheet" href="${ctx}/css/uniform.css" />
<link rel="stylesheet" href="${ctx}/css/select2.css" />
<link rel="stylesheet" href="${ctx}/css/unicorn.main.css" />
<link rel="stylesheet" href="${ctx}/css/common.css" />
<script src="${ctx}/js/jquery-1.9.0.js"></script>
</head>
<body>
<div class="container" id="businessEname_div">
<div class="row">
<div class="span1"></div>
<div class="span10">
<div class="widget-box">
<div class="widget-title">
<h5>商圈列表</h5>
</div>
<div class="widget-content nopadding">
<table class="table table-bordered table-striped table-hover data-table">
<thead>
<tr>
<th style="vertical-align:middle;width:10px;"><input type="checkbox" name="chkAll" id="chkAll"></th>
<th>logo</th>
<th>名稱</th>
<th>英文名</th>
<th>註冊日期</th>
</tr>
</thead>
<tbody id="tby">
</tbody>
</table>
</div>
</div>
<div class="pagination">
<input type="hidden" id="totalPage_input"/>
<ul>
<li><a href="javascript:void(0);" id="firstPage">首頁</a></li>
<li><a href="javascript:void(0);" id="shang">上一頁</a></li>
<li><a href="javascript:void(0);" id="xia">下一頁</a></li>
<li><a href="javascript:void(0);" id="lastPage">末頁</a></li>
<li>共<lable id="totalPage"></lable>頁</li>
<li>第<lable id="currentPage"></lable>頁</li>
<li>共<lable id="totalRows"></lable>條記錄</li>
</ul>
</div>
</div>
<div class="span1"></div>
</div>
</div>
<script type="text/javascript">
/**
* V1.0
*/
$(document).ready(function() {
var currentPage=1; //第幾頁
var numPerPage=5; //每頁顯示條數
//分頁查詢
var queryByPage=function(){
$("#tby tr").remove();
$.ajax({
type: "post",
url: "${ctx}/business/queryPageBusiness.do?¤tPage="+currentPage+"&numPerPage="+numPerPage,
dataType: "json", /*這句可用可不用,沒有影響*/
contentType: "application/json; charset=utf-8",
success: function (data) {
var array=data.businessList;
var tby=$("#tby");
var totalPage=data.totalPage;
$("#totalPage_input").val(totalPage);
$("#currentPage").html(currentPage);
$("#totalRows").html(data.totalRows);
$("#totalPage").html(totalPage);
//迴圈json中的資料
for(var i=0,len=array.length;i<len;i++){
var td1=$("<td style='vertical-align:middle;width:10px;'><input type='checkbox' name='chk'></td>");
var td2 =$("<td width='140px'><img src='http://blog.csdn.net/huahuagongzi9999/article/details/"+array[i].businessPic+"' style='width:135px;height:125px;background-color: none;border: none;'></td>");
var td3 =$("<td>"+array[i].businessName+"</td>");
var td4 =$("<td>"+array[i].businessEname+"</td>");
var td5 =$("<td>"+array[i].createTime+"</td>");
var tr=$("<tr></tr>");
tr.append(td1).append(td2).append(td3).append(td4).append(td5);
tr.appendTo(tby);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
//初始化列表
queryByPage(currentPage,numPerPage);
//首頁
$("#firstPage").bind("click",function(){
currentPage=1;
queryByPage(currentPage,numPerPage);
});
//上一頁
$("#shang").click(function(){
if(currentPage==1){
alert("已經到達第一頁");
return ;
}else{
currentPage--;
queryByPage();
}
});
//下一頁
$("#xia").click(function(){
if(currentPage==$("#totalPage_input").val()){
alert("已經到達最後一頁");
return ;
}else{
currentPage++;
queryByPage();
}
});
//末頁
$("#lastPage").bind("click",function(){
currentPage=$("#totalPage_input").val();
queryByPage(currentPage,numPerPage);
});
//隔行變色
function changeColor(){
$("#tby>tr:odd").css("background-color","#E9EBEF");
$("#tby>tr:even").css("background-color","#ffffff");
}
});
</script>
</body>
</html>