Ajax分页 Spring MVC + Hibernate

前端之家收集整理的这篇文章主要介绍了Ajax分页 Spring MVC + Hibernate前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

效果图:


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,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,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,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,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 {
	
	@Resource
	private 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,response);
		
		return "/srm_management/inc/srmUser_table";
	}

}

具体查询代码

	@Override
	public Page<SrmUser> getUserList(String enterpriseName,String vendorName,String userName,String status,String fromCreateDate,String toCreateDate,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(),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相关文章