SSM下的分页

页面:list.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<script src="<c:url value="/js/jquery-ui.js"/>"></script>
<script type="text/javascript">
function buttonSubmit(url){
	document.form.action=url;
	document.form.submit();
}
function del(url){
	if(confirm("确定要删除该活动?")){
		document.form.action=url;
		document.form.submit();
	}
}
</script>
<div class="app-content">
	<ul class="breadcrumb">
		<li>你当前的位置</li>
		<tags:breadcrumb />
		<li>列表</li>
	</ul>
	<div class="panel-group" id="accordion" role="tablist"
		aria-multiselectable="true">
		<div class="panel panel-default">
			<div class="panel-heading" role="tab" id="headingOne">
				<h4 class="panel-title" id="-collapsible-group-item-#1-">
					<a data-toggle="collapse" data-parent="#accordion"
						href="#collapseOne" aria-expanded="true"
						aria-controls="collapseOne" class=""> 活动方案列表 </a>
				</h4>
			</div>
			<div id="collapseOne" class="panel-collapse collapse in"
				role="tabpanel" aria-labelledby="headingOne" aria-expanded="true">
				<div class="panel-body">
					<form name="form" class="form-inline"
						action="<c:url value="/business/activity/list.do"/>" method="post">
						<fieldset>
							<div class="form-group form-group-sm  right20">
								<label class="control-label" for="businessId">商户:</label> <select
									class="form-control" id="businessId" name="businessId">
								<option value="">--全部--</option>
								<c:forEach items="${business}" var="busines">
									<option value="${busines.id }" <c:if test="${condition.businessId == busines.id}">selected="selected"</c:if>>${busines.name }</option>
								</c:forEach>
							</select>
							</div>
							<div class="form-group form-group-sm  right20">
								<label class="control-label" for="type">类型:</label> <select
									class="form-control" id="type" name="type">
									<option value="">--全部--</option>
									<option value="0" <c:if test="${condition.type == 0}">selected="selected"</c:if>>免费领取</option>
									<option value="1" <c:if test="${condition.type == 1}">selected="selected"</c:if>>商品秒杀</option>
									<option value="2" <c:if test="${condition.type == 2}">selected="selected"</c:if>>限时抢购</option>
									<option value="3" <c:if test="${condition.type == 3}">selected="selected"</c:if>>积分兑换</option>
									<option value="4" <c:if test="${condition.type == 4}">selected="selected"</c:if>>抽奖活动</option>
									<option value="5" <c:if test="${condition.type == 5}">selected="selected"</c:if>>转盘活动</option>
									<option value="6" <c:if test="${condition.type == 6}">selected="selected"</c:if>>会员商品</option>
									<option value="7" <c:if test="${condition.type == 7}">selected="selected"</c:if>>优惠券</option>
									<option value="8" <c:if test="${condition.type == 8}">selected="selected"</c:if>>注册送积分</option>
									<option value="9" <c:if test="${condition.type == 9}">selected="selected"</c:if>>合作方抽奖</option>
									<option value="10" <c:if test="${condition.type == 10}">selected="selected"</c:if>>看广告抽奖</option>
								</select>
							</div>
							<div class="form-group form-group-sm  right20">
								<label class="control-label" for="title">标题:</label>
								<input class="form-control" type="text" id="title"
									name="title" value="${condition.title}">
							</div>
							<div class="form-group form-group-sm  right20">
								<label class="control-label" for="status">状态:</label> <select
									class="form-control" id="status" name="status">
									<option value="">--全部--</option>
									<option value="0" <c:if test="${condition.status == 0}">selected="selected"</c:if>>上线</option>
									<option value="1" <c:if test="${condition.status == 1}">selected="selected"</c:if>>下线</option>
								</select>
							</div>
							<div class="form-group form-group-sm">
								<button type="submit" class="btn btn-primary btn-sm">
									<i class="icon-search icon-white"></i> 查  询 
								</button>
								  
							</div>
							<div class="form-group form-group-sm">
								<button type="button" οnclick="buttonSubmit('add.do')"
									class="btn btn-primary btn-sm">
									<i class="icon-search icon-white"></i> 添加方案
								</button>
								  
							</div>
						</fieldset>
					</form>
					<table class="table table-striped table-bordered top20">
						<thead>
							<tr>
								<th>序号</th>
								<th>商户</th>
								<th>活动类型</th>
								<th>商品名称</th>
								<th>标题</th>
								<th>参与频率</th>
								<th>状态</th>
								<th>上线时间</th>
								<th>下线时间</th>
								<th>操作</th>
							</tr>
						</thead>
						<c:if test="${null != activityInfos}">
							<c:forEach var="item" items="${activityInfos}">
								<tr>
									<td class="center">${item.id}</td>
									<td class="center">
										<c:forEach items="${business }" var="busines">
											<c:if test="${busines.id == item.businessId }">${busines.name }</c:if>
										</c:forEach>
									</td>
									<td class="center">
										<c:choose>
											<c:when test="${item.type == 0}">免费领取</c:when>
											<c:when test="${item.type == 1}">商品秒杀</c:when>
											<c:when test="${item.type == 2}">限时抢购</c:when>
											<c:when test="${item.type == 3}">积分兑换</c:when>
											<c:when test="${item.type == 4}">抽奖活动</c:when>
											<c:when test="${item.type == 5}">转盘活动</c:when>
											<c:when test="${item.type == 6}">会员商品</c:when>
											<c:when test="${item.type == 7}">优惠券</c:when>
											<c:when test="${item.type == 8}">注册送积分</c:when>
											<c:when test="${item.type == 9}">合作方抽奖</c:when>
											<c:when test="${item.type == 10}">看广告抽奖</c:when>
										</c:choose>
									</td>
									<td class="center">
										<c:if test="${item.type != 4 && item.type != 5}">
											<c:forEach items="${commoditys}" var="commodity">
												<c:if test="${commodity.id == item.cid }">
													${commodity.name}
												</c:if>
											</c:forEach>
										</c:if>
										<c:if test="${item.type == 4 or item.type == 9 or item.type == 10}">
											<a href="<c:url value="/business/lottery/list.do?aid=${item.id}"/>">查询奖品</a>
										</c:if>
										<c:if test="${item.type == 5}">
											<a href="<c:url value="/business/turntable/list.do?aid=${item.id}"/>">查询奖品</a>
										</c:if>
									</td>
									<td class="center" title="${item.title}">
										<c:if test="${fn:length(item.title)<=5}">
											${item.title}
										</c:if>
										<c:if test="${fn:length(item.title)>5}">
											${fn:substring(item.title, 0, 5)}...
										</c:if>
									</td>
									<td class="center">
										${item.frequency}
									</td>
									<td class="center">
										<c:choose>
											<c:when test="${item.status == 0}">上线</c:when>
											<c:otherwise>下线</c:otherwise>
										</c:choose>
									</td>
									<td class="center">
										<fmt:formatDate value="${item.onlineTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
									<td class="center">
										<fmt:formatDate value="${item.offlineTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
									</td>
									<td>
										<%--<c:if test="${item.type == 1}">
											<button type="submit" class="btn btn-primary btn-xs"
													οnclick="buttonSubmit('/SG-web/business/spike/findByComm.do?activityId=${item.id}')">
												<i class="icon-edit icon-white"></i>设置秒杀规则
											</button>
										</c:if>--%>
										<c:if test="${item.status == 0 }">
											<button type="submit" class="btn btn-primary btn-xs"
												οnclick="buttonSubmit('offline.do?id=${item.id}')">
												<i class="icon-edit icon-white"></i>下线
											</button>
										</c:if>
										<c:if test="${item.status == 1 }">
											<button type="submit" class="btn btn-primary btn-xs"
												οnclick="buttonSubmit('online.do?id=${item.id}')">
												<i class="icon-edit icon-white"></i>上线
											</button>
										</c:if>
										<button type="submit" class="btn btn-primary btn-xs"
											οnclick="buttonSubmit('edit.do?id=${item.id}')">
											<i class="icon-edit icon-white"></i>编辑
										</button>
										<c:if test="${item.status == 1 }">
											<button type="submit" class="btn btn-primary btn-xs"
												οnclick="del('delete.do?id=${item.id}')">
												<i class="icon-edit icon-white"></i>删除
											</button>
										</c:if>
									</td>
								</tr>
							</c:forEach>
						</c:if>
					</table>
					<div style="text-align: right">
						<tags:page page1="${page}" />
					</div>
				</div>
			</div>
		</div>
	</div>
</div

拦截器:com.fire.SG.web.interceptor/PageQueryInterceptor


package com.fire.SG.web.interceptor;

import com.fire.SG.web.util.page.Page;
import com.fire.SG.web.util.page.PageUtil;
import com.google.common.base.Joiner;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.mapping.MappedStatement.Builder;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;


import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by yb
 */
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class PageQueryInterceptor implements Interceptor {
    private static final List<ResultMapping> EMPTY_RESULTMAPPING = new ArrayList<ResultMapping>(0);
    @SuppressWarnings("rawtypes")
public Object intercept(Invocation invocation) throws Throwable {
        //Page对象获取,“信使”到达拦截器!
        Page page = PageUtil.getPage();
        //不分页直接返回
        if(page==null)
            return invocation.proceed();


        //清空分页参数
        PageUtil.removePage();


        //当前环境 MappedStatement,BoundSql,及sql取得
        MappedStatement mappedStatement=(MappedStatement)invocation.getArgs()[0];
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        String originalSql = boundSql.getSql().trim();


        //查询总数
        String countSql = getCountSql(originalSql);
        BoundSql countBS = newBoundSql(mappedStatement, boundSql, countSql);
        MappedStatement countMs = newMappedStatement(mappedStatement, new BoundSqlSqlSource(countBS),true);
        invocation.getArgs()[0] = countMs;
        Object result = invocation.proceed();
        //设置总数
        page.setTotalRecord((Integer) ((List) result).get(0));


        //分页查询
        int pageNo   = page.getPageNo();
        int pageSize = page.getPageSize();
        //分页计算
        //对原始Sql追加limit
        int offset = (pageNo - 1) * pageSize;
        BoundSql newBoundSql = newBoundSql(mappedStatement, boundSql, originalSql + " limit " + offset + "," + pageSize);
        MappedStatement pageMs = newMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql),false);
        invocation.getArgs()[0]= pageMs;


        return invocation.proceed();




    }






    /**
     * 新建MappedStatement对象
     */
    private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource,boolean count) {
        Builder builder = new Builder(ms.getConfiguration(),ms.getId(),newSqlSource,ms.getSqlCommandType());


        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if((ms.getKeyProperties()!=null)){
            builder.keyProperty(Joiner.on(",").join(ms.getKeyProperties()));
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        if (count) {
            //count查询返回值int
            List<ResultMap> resultMaps = new ArrayList<ResultMap>();
            ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), int.class, EMPTY_RESULTMAPPING).build();
            resultMaps.add(resultMap);
            builder.resultMaps(resultMaps);
        } else {
            builder.resultMaps(ms.getResultMaps());
        }
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }


    /**
     * 复制BoundSql对象
     */
    private BoundSql newBoundSql(MappedStatement ms, BoundSql boundSql, String sql) {
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        return newBoundSql;
    }


    /**
     * 根据原Sql语句获取对应的查询总记录数的Sql语句
     */
    private String getCountSql(String sql) {
        String copy = sql;
        Pattern pattern = Pattern.compile("order\\s+by.*(asc|desc)?",Pattern.MULTILINE&Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(copy);
        copy = matcher.replaceAll("");
        return "SELECT COUNT(*) FROM (" + copy + ") aliasForPage";
    }


    public class BoundSqlSqlSource implements SqlSource {
        BoundSql boundSql;
        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
    public Object plugin(Object arg0) {
//        return this;
        return Plugin.wrap(arg0, this);
    }
    public void setProperties(Properties arg0) {
    }


    public static void main(String[] args) {
        String s = "select c1,c2 from tbl_test_col Where c1=? order by c2 desc";
        System.out.println(testGetCountSql(s));
    }


    //test
    private static String testGetCountSql(String sql) {
        String copy = sql;
        Pattern pattern = Pattern.compile("order\\s+by.*(asc|desc)?",Pattern.CASE_INSENSITIVE&Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(copy);
        copy = matcher.replaceAll("");
        return "SELECT COUNT(*) FROM (" + copy + ") aliasForPage";
    }


PageUtil  Page

package com.fire.SG.web.util.page;


import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;


/**
 * Created by yubin
 */
public class Page {
    private static final Logger logger = LoggerFactory.getLogger(Page.class);


    public static Integer DEFAULT_PAGESIZE = 15;
    private int pageNo;                    //当前页码
    private int pageSize;                  //每页行数
    private int totalRecord;               //总记录数
    private int totalPage;                 //总页数


    private Map<String, String> params;            //查询条件
    private Map<String, List<String>> paramLists;  //数组查询条件
    private String searchUrl;                      //Url地址
    private String pageNoDisp;                     //可以显示的页号(分隔符"|",总页数变更时更新)


    public Page() {
        pageNo = 1;
        pageSize = DEFAULT_PAGESIZE;
        totalRecord = 0;
        totalPage = 0;
        params = Maps.newHashMap();
        paramLists = Maps.newHashMap();
        searchUrl = "";
        pageNoDisp = "";
    }
    public Page(int pageNo,int pageSize){
        this.pageNo = pageNo>0?pageNo:1;
        this.pageSize = pageSize>0?pageSize:DEFAULT_PAGESIZE;
        totalRecord = 0;
        totalPage = 0;
        params = Maps.newHashMap();
        paramLists = Maps.newHashMap();
        searchUrl = "";
        pageNoDisp = "";
    }


    public void initParams(HttpServletRequest req){
        String uri = req.getRequestURI();
        int pot = uri.indexOf(".do");
        // 从uri中抽取右侧"/"后字符串作为的acton名 例子中对应的是 "users"
        searchUrl=uri.substring(0,pot + 3);
        // 这里是核心代码:遍历 req.getParameterMap() 提取请求参数,要注意数组的情况
        for (Object key : req.getParameterMap().keySet()) {
            String[] args = req.getParameterValues(key.toString());
            if (args.length > 1) {
                paramLists.put(key.toString(), convertParamArr(args, req));
            } else {
                params.put(key.toString(), convertIsoToUtf8(req.getParameter(key.toString()), req));
            }
        }


        if (params.get("pageNo") == null) {
            params.put("pageNo", "1");    // 当前页 缺省值设定
        } else {
            pageNo= Integer.parseInt(params.get("pageNo"));
            // 点击分页标签时的请求 编辑totalRecord 项目(避免重复查询总记录数)
            totalRecord=Integer.parseInt(params.get("totalRecord"));
        }
    }




    /**
     * GET请求时,单个入参的转码处理
     */
    private static String convertIsoToUtf8(String strIn, HttpServletRequest request) {
        if (strIn == null || !request.getMethod().equalsIgnoreCase("get")) {
            return strIn;
        }
        try {
            return new String(strIn.getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            return strIn;
        }
    }


    /**
     * GET请求时,数组型入参的转码处理
     */
    private static List<String> convertParamArr(String[] param,
                                                HttpServletRequest request) {
        List<String> list = Lists.newArrayList();
        if (param != null) {
            for (String p : param) {
                String convertP = convertIsoToUtf8(p, request);
                if (!list.contains(convertP)) {
                    list.add(convertP);
                }
            }
        }
        return list;
    }


    /**
     * 查询条件转JSON
     */
    public String getParaJson() {
        Map<String, Object> map = Maps.newHashMap();
        for (String key : params.keySet()) {
            if (params.get(key) != null) {
                map.put(key, params.get(key));
            }
        }
        String json = "";
        try {
            json = JSON.toJSONString(map);
        } catch (Exception e) {
            logger.error("转换JSON失败", params, e);
        }
        return json;
    }


    /**
     * 数组查询条件转JSON
     */
    public String getParaListJson() {
        Map<String, Object> map = Maps.newHashMap();
        for (String key : paramLists.keySet()) {
            List<String> lists = paramLists.get(key);
            if (lists != null && lists.size() > 0) {
                map.put(key, lists);
            }
        }
        String json = "";
        try {
            json = JSON.toJSONString(map);
        } catch (Exception e) {
            logger.error("转换JSON失败", params, e);
        }
        return json;
    }


    /**
     * 总件数变化时,更新总页数并计算显示样式
     */
    private void refreshPage() {
        //总页数计算
        totalPage = totalRecord % pageSize == 0 ? totalRecord / pageSize : (totalRecord / pageSize + 1);
        //防止超出最末页(浏览途中数据被删除的情况)
        if (pageNo > totalPage && totalPage != 0) {
            pageNo = totalPage;
        }
        pageNoDisp = computeDisplayStyleAndPage();
    }


    /**
     * 计算页号显示样式
     * 这里实现以下的分页样式("[]"代表当前页号),可根据项目需求调整
     * [1],2,3,4,5,6,7,8..12,13
     * 1,2..5,6,[7],8,9..12,13
     * 1,2..6,7,8,9,10,11,12,[13]
     */
    private String computeDisplayStyleAndPage() {
        List<Integer> pageDisplays = Lists.newArrayList();
        if (totalPage <= 11) {
            for (int i = 1; i <= totalPage; i++) {
                pageDisplays.add(i);
            }
        } else if (pageNo < 7) {
            for (int i = 1; i <= 8; i++) {
                pageDisplays.add(i);
            }
            pageDisplays.add(0);// 0 表示 省略部分(下同)
            pageDisplays.add(totalPage - 1);
            pageDisplays.add(totalPage);
        } else if (pageNo > totalPage - 6) {
            pageDisplays.add(1);
            pageDisplays.add(2);
            pageDisplays.add(0);
            for (int i = totalPage - 7; i <= totalPage; i++) {
                pageDisplays.add(i);
            }
        } else {
            pageDisplays.add(1);
            pageDisplays.add(2);
            pageDisplays.add(0);
            for (int i = pageNo - 2; i <= pageNo + 2; i++) {
                pageDisplays.add(i);
            }
            pageDisplays.add(0);
            pageDisplays.add(totalPage - 1);
            pageDisplays.add(totalPage);
        }
        return Joiner.on("|").join(pageDisplays.toArray());
    }
    public int getPageNo() {
        return pageNo;
    }


    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }


    public int getPageSize() {
        return pageSize;
    }


    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }


    public int getTotalRecord() {
        return totalRecord;
    }


    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
        refreshPage();
    }


    public int getTotalPage() {
        return totalPage;
    }


    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }


    public Map<String, String> getParams() {
        return params;
    }


    public void setParams(Map<String, String> params) {
        this.params = params;
    }


    public Map<String, List<String>> getParamLists() {
        return paramLists;
    }


    public void setParamLists(Map<String, List<String>> paramLists) {
        this.paramLists = paramLists;
    }


    public String getSearchUrl() {
        return searchUrl;
    }


    public void setSearchUrl(String searchUrl) {
        this.searchUrl = searchUrl;
    }


    public String getPageNoDisp() {
        return pageNoDisp;
    }


    public void setPageNoDisp(String pageNoDisp) {
        this.pageNoDisp = pageNoDisp;
    }
}


package com.fire.SG.web.util.page;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;


/**
 * 只能对接下来的一个进行分页,
 * Created by yubin
 */
public class PageUtil {
    private static ThreadLocal<Page> threadPage = new ThreadLocal<Page>();


    public static Page getPage () {
        return threadPage.get();
    }


    public static Page removePage () {
        Page page = threadPage.get();
        threadPage.set(null);
        return page;
    }


    /**
     * 开始分页,只能对接下来的一个进行分页
     */
    public static Page startPage(Page page){
        threadPage.set(page);
        initPageParam(page);
        return page;
    }


    /**
     * 开始分页,只能对接下来的一个进行分页
     */
    public static Page startPage(int pageNo,int pageSize) {
        Page page = new Page(pageNo,pageSize);
        return startPage(page);
    }


    private static void initPageParam(Page page){
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        page.initParams(req);
    }


}





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值