標籤:
:
1. 添加公用類、方法、代碼
1. 分頁類:Page.java
package cn.com.aperfect.sso.base.dao;import java.util.ArrayList;import java.util.List;public class Page<T> {// 當前頁數private int currentPage;// 記錄位移量private int offset;// 總頁數private int totalsPage;// 每頁顯示記錄條數private int pageSize;// 總記錄條數private int totalsCount;// 查詢返回結果private List<T> result = new ArrayList<T>();// 分頁連結private String uri;public Page(){}public Page(int currentPage, int pageSize) {this.currentPage = currentPage;this.pageSize = pageSize;this.offset = (currentPage-1)*pageSize;}public String getUri() {return uri;}public void setUri(String uri) {this.uri = uri;}public int getCurrentPage() {return currentPage;}public void setCurrentPage(int currentPage) throws Exception {if (currentPage < 0) {currentPage = 0;}this.currentPage = currentPage;}public int getTotalsPage() {try {if (totalsCount % pageSize == 0) {totalsPage = totalsCount / pageSize;} else {totalsPage = (totalsCount / pageSize) + 1;}} catch (Exception e) {throw new RuntimeException(e);}return totalsPage;}public void setTotalsPage(int totalsPage) {if (totalsPage < 0) {totalsPage = 0;}this.totalsPage = totalsPage;}public int getPageSize() {return pageSize;}public void setPageSize(int pageSize) {if (pageSize <= 0) {pageSize = 20;}this.pageSize = pageSize;}public int getTotalsCount() {return totalsCount;}public void setTotalsCount(int totalsCount) {if (totalsCount < 0) {totalsCount = 0;}this.totalsCount = totalsCount;}public List<T> getResult() {return result;}public void setResult(List<T> result) {this.result = result;}public int getOffset() {return offset;}public void setOffset(int offset) {this.offset = offset;}}
2. 公用的DAO / DAOImpl
DAO
/** * <b>function:</b> 傳入查詢語句和查詢參數名key對應value,page指定currentPage和pageSize * @param queryHql 查詢語句 * @param paramMap 參數 * @param page 當前頁和每頁幾條資料 * @throws Exception */public Page<T> showPage(String queryHql,String countHql, Map<String, Object> paramMap,int currentPage, int pageSize) throws Exception;
IMPL
public Page<T> showPage(String queryHql, String countHql, Map<String, Object> paramMap, int currentPage, int pageSize) throws Exception {Page<T> page = new Page<T>(currentPage, pageSize);try {int dataCount = queryForInt(countHql, paramMap);page.setResult(queryForList(queryHql, paramMap, page.getOffset(),pageSize));page.setTotalsCount(dataCount);} catch (Exception e) {throw new RuntimeException(e);}return page;}private final int queryForInt(String queryIntHQL,Map<String, Object> paramMap){Query query = this.getSession().createQuery(queryIntHQL);setQueryParameterValues(paramMap, query);int result = Integer.parseInt(query.uniqueResult().toString());return result;}private final List<T> queryForList(String queryHql,Map<String, Object> paramMap, int offset,int pageSize){Query query = this.getSession().createQuery(queryHql);setQueryParameterValues(paramMap, query);if (offset>=0) {query.setFirstResult(offset);}if (pageSize>0) {query.setMaxResults(pageSize);}return query.list(); }private final void setQueryParameterValues(Map<String, Object> paramMap,Query query){if (CollectionUtil.isEmpty(paramMap))return ;for (Entry<String, Object> entry : paramMap.entrySet()) {query.setParameter(entry.getKey(), entry.getValue());}}
2. 代碼(Controller)
Controller分別有兩個請求的方法,請求的地址是不一樣的。
一個用於初始化頁面時候請求,另外一個是分頁時候Ajax用的請求。
(第一個請求返回的是整個頁面,ajax請求返回的只是一個抽取出來的*table.jsp,所以要兩個請求,只是返回的jsp不一樣。只是使用了js將原來頁面的table替換掉新的而已)
方法主體是一樣的。
@Controller@RequestMapping("/srmUser")public class SrmUserController {@Resourceprivate ISrmUserService srmUserService;private void doSearch(HttpServletRequest request, HttpServletResponse response) throws Exception{int currentPage = ServletRequestUtils.getIntParameter(request, "currentPage", 1);int pageSize = ServletRequestUtils.getIntParameter(request, "pageSize", 10);//前台資料傳到後台查詢String enterpriseName = ServletRequestUtils.getStringParameter(request, "enterpriseName");String vendorName = ServletRequestUtils.getStringParameter(request, "vendorName");String userName = ServletRequestUtils.getStringParameter(request, "userName");String status = ServletRequestUtils.getStringParameter(request, "status");String fromCreateDate = ServletRequestUtils.getStringParameter(request, "fromCreateDate");String toCreateDate = ServletRequestUtils.getStringParameter(request, "toCreateDate");Page<SrmUser> page = srmUserService.searchUserList(enterpriseName,vendorName,userName,status,fromCreateDate,toCreateDate, currentPage, pageSize);//資料返回前台request.setAttribute("enterpriseName", enterpriseName);request.setAttribute("vendorName", vendorName);request.setAttribute("userName", userName);request.setAttribute("status", status);request.setAttribute("fromCreateDate", fromCreateDate);request.setAttribute("toCreateDate", toCreateDate);request.setAttribute("toCreateDate", toCreateDate);request.setAttribute("userListDto", page.getResult());request.setAttribute("pageEntity", page);}@RequestMapping("/searchUser")public String searchUser(HttpServletRequest request, HttpServletResponse response) throws Exception {doSearch(request, response);return "/srm_management/srmUser_manage";}@RequestMapping("/ajaxSearchUser")public String ajaxSearchUser(HttpServletRequest request, HttpServletResponse response) throws Exception {doSearch(request, response);return "/srm_management/inc/srmUser_table";}}
具體查詢代碼
@Overridepublic Page<SrmUser> getUserList(String enterpriseName, String vendorName,String userName, String status, String fromCreateDate,String toCreateDate, int currentPage, int pageSize) throws Exception {Page<SrmUser> page = null;StringBuffer sbHQL = new StringBuffer();StringBuffer countHQL = new StringBuffer();Map<String, Object> paramMap = new HashMap<String, Object>();try {sbHQL.append("from SrmUser u where 1=1 "); countHQL.append("select count(*) from SrmUser u where 1=1 "); if (!StringUtil.isEmpty(enterpriseName)) {sbHQL.append(" and u.enterprise.enterpriseName like :enterpriseName ");countHQL.append(" and u.enterprise.enterpriseName like :enterpriseName ");paramMap.put("enterpriseName", "%"+enterpriseName+"%");}if (!StringUtil.isEmpty(vendorName)) { sbHQL.append(" and u.userId in (");sbHQL.append("select userId from SrmUserVendor s where s.vendorId in (");sbHQL.append("select vendorId from SrmVendor v where v.vendorName like :vendorName)) ");countHQL.append(" and u.userId in (");countHQL.append("select userId from SrmUserVendor s where s.vendorId in (");countHQL.append("select vendorId from SrmVendor v where v.vendorName like :vendorName)) ");paramMap.put("vendorName", "%"+vendorName+"%");}if (!StringUtil.isEmpty(userName)) {sbHQL.append(" and u.userName like :userName ");countHQL.append(" and u.userName like :userName ");paramMap.put("userName", "%"+userName+"%");}if (!StringUtil.isEmpty(status)) {sbHQL.append(" and u.status = :status ");countHQL.append(" and u.status = :status ");paramMap.put("status", Integer.parseInt(status));}if (!StringUtil.isEmpty(fromCreateDate)) {sbHQL.append(" and u.createDate >= :fromCreateDate ");countHQL.append(" and u.createDate >= :fromCreateDate ");paramMap.put("fromCreateDate", fromCreateDate);}if (!StringUtil.isEmpty(toCreateDate)) {sbHQL.append(" and u.createDate < :toCreateDate ");countHQL.append(" and u.createDate < :toCreateDate ");//toCreateDate 要加上一天java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(toCreateDate);Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.DATE,1); date= calendar.getTime(); paramMap.put("toCreateDate", date);}sbHQL.append(" order by u.userId asc ");page = showPage(sbHQL.toString(), countHQL.toString(), paramMap, currentPage, pageSize);
3. 前台JSP等
Jsp要分成兩部分,一部分是整體的第一次請求的時候的整體頁面。
另一部分是*_table.jsp 就是要分頁的那個table。
只要在整體裡面抽出*_table.jsp頁面就可以,然後整體頁面裡面引用*_table.jsp頁面。
將要ajax請求的table替換成下面,這個<span>是用於後面Ajax請求成功的時候要替換的標識
<span id="resourceSpan"> <jsp:include page="inc/srmUser_table.jsp" /> </span>
後台將整個*_table.jsp 頁面返回到前台的<span>裡面。
*.table.jsp
<%@ page language="java" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%><table class="details"><tr class="noticClsSrm"><td>企業</td><td>使用者名稱</td><td>建立者</td><td>建立時間</td><!-- <td>最後編輯者</td><td>最後更新時間</td> --><td>狀態</td></tr><c:forEach var="userDto" items="${requestScope.userListDto}"><tr><td>${userDto.enterprise.enterpriseName }</td><td>${userDto.userName }</td><td>${userDto.creatorName }</td><td><fmt:formatDate value="${userDto.createDate }" pattern="yyyy-MM-dd"/> </td><%-- <td>${userDto.editorName }</td><td><fmt:formatDate value="${userDto.updateDate }" pattern="yyyy-MM-dd"/> </td> --%><td><c:if test="${userDto.status==0 }">啟動</c:if><c:if test="${userDto.status==1 }">凍結</c:if><c:if test="${userDto.status==2 }">刪除</c:if></td></tr></c:forEach></table><jsp:include page="../../commons/page_ajax.jsp"/><script type="text/javascript"> //分頁跳轉var totalsPage = '${pageEntity.totalsPage}';if (totalsPage == '') totalsPage = 1;function ajaxGotoPage(currentPage) {if (currentPage == null || currentPage == "") return;if (isNaN(currentPage)) return;if (currentPage < 1) currentPage = 1;else if ((currentPage > totalsPage) || (currentPage==${pageEntity.currentPage})) return;var resourceSpan = $("#resourceSpan");resourceSpan.html("<br/><img src='${pageContext.request.contextPath }/commons/images/blue-loading.gif'/>");$.ajax({url:'${pageContext.request.contextPath }/v/srmUser/ajaxSearchUser',type:'post',data:{currentPage:currentPage,enterpriseName:$("#enterpriseName").val(),vendorName:$("#vendorName").val(),userName:$("#userName").val(),status:$("#status").val(),fromCreateDate:$("#fromCreateDate").val(),toCreateDate:$("#toCreateDate").val()},dataType:'text',timeout:60000,error: function(e) {alert(e);},success: function(result){resourceSpan.html(result);}});}function gotoPageByInput(){var currentPage=document.getElementById('goInput').value;ajaxGotoPage(parseInt(currentPage));}</script>
page_ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><style><span style="white-space:pre"></span>.goSearchButton{background:url(<c:url value='/resources/images/ok.gif' />);border:0 none;height:19px;margin:0 0 0 5px;text-indent:-999px;width:37px;}<span style="white-space:pre"></span>div.yk-pager {text-align: right;padding:3px 0px;margin: 3px 0px;color:#666666;}<span style="white-space:pre"></span>div.yk-pager a{color: #036CB4;margin-right: 2px;padding:2px 5px;text-decoration: none;border:1px solid #929196;}<span style="white-space:pre"></span>div.yk-pager a:hover {padding:2px 5px;margin-right: 2px;background-color:#ccdaf3;border: #a0a0a0 1px solid;}<span style="white-space:pre"></span>div.yk-pager a:active {padding:2px 5px;margin-right: 2px;background-color:#ccdaf3;border: #a0a0a0 1px solid;}<span style="white-space:pre"></span>div.yk-pager span.current {font-weight: bold;color: #FFFFFF;padding:2px 5px;margin-right: 2px;background-color:#6390cb;border:1px solid #3d68a0}<span style="white-space:pre"></span>div.yk-pager span.disabled {color: #ccc;margin-right: 2px;border:1px solid #f3f3f3;padding:2px 5px;}<span style="white-space:pre"></span>div.yk-pager .goInput{border:1px solid #99bbe8;color:#000000;font-family:Tahoma,SimSun,Arial;height:18px;margin:0 5px;text-align:center;vertical-align:top;width:30px;}<span style="white-space:pre"></span>div.yk-pager .goButton{background:url(skin/ok.gif);border:0 none;height:19px;margin:0 0 0 5px;text-indent:-999px;width:37px;}</style><div class="yk-pager"><a href="javascript:ajaxGotoPage(1);">首頁</a><a href="javascript:ajaxGotoPage(${pageEntity.currentPage-1});"> ?上一頁</a> <a href="javascript:ajaxGotoPage(${pageEntity.currentPage+1});"> 下一頁? </a><a href="javascript:ajaxGotoPage(${pageEntity.totalsPage });"> 末頁</a>總${pageEntity.totalsCount }條,第${pageEntity.currentPage}/${pageEntity.totalsPage }頁,到第<input size=2 id="goInput" value=''/>頁,<input type="button" class="goButton" onclick="gotoPageByInput();"/></div>
ok.gif
Ajax分頁 Spring MVC + Hibernate