项目用到ajax技术的查询,查询结果很多时候要分页展示。这两天摸索了一下,在这里做一总结,方便自己随时查看,
也方便后人参考。
这里的顺序遵从从前台页面到后台控制器,业务层,Dao层,Mapper
下面先讲页面,页面js代码如下:
- <span style="font-size:14px;">/* 全局变量 */
- var userCount;//符合查找条件的用户总页数,分页参考
- var pageIndex = 0;//当前页,默认为0
- var pageSize = 8;//每页显示个数为8
- //按条件查找用户
- function searchUser(index,size) {
- var findTerm = $("#serchTerm").val();
- var provinceId = $('#province').val();
- var cityId = $('#city').val();
- $.ajax({
- type : "POST",
- url : "user/findContactsAjax",
- cache : false,
- data : {
- provinceId : provinceId,
- cityId : cityId,
- pageIndex:index,
- pageSize:size
- },
- async : true,
- error : function() {
- alert("网络异常!");
- },
- success : function(data) {
- <span style="white-space:pre"> </span>userCount=Math.ceil(data[0].userCount/8);<span style="white-space:pre"> </span>var page='<div id="userPage" align="center" ><font size="2">共'
- +userCount+'页</font> <font size="2">第'
- +(pageIndex+1)+'页</font> <a href="javascript:void" onclick="GoToFirstPage()" id="aFirstPage" >首页</a> '
- +'<a href="javascript:void" onclick="GoToPrePage()" id="aPrePage" >上一页</a> '
- +'<a href="javascript:void" onclick="GoToNextPage()" id="aNextPage" >下一页</a> '
- +'<a href="javascript:void" onclick="GoToEndPage()" id="aEndPage" >尾页</a> ';
- page+='</div>';
- $("#serchResult").append(page);
- document.getElementById("dltitle").innerHTML = "查找结果如下";
- }
- }
- });
- }
- //首页
- function GoToFirstPage() {
- pageIndex = 0;
- searchUser( pageIndex, pageSize);
- }
- //前一页
- function GoToPrePage() {
- pageIndex -= 1;
- pageIndex = pageIndex >= 0 ? pageIndex : 0;
- searchUser( pageIndex, pageSize);
- }
- //后一页
- function GoToNextPage() {
- if (pageIndex + 1 < userCount) {
- pageIndex += 1;
- }
- searchUser( pageIndex, pageSize);
- }
- //尾页
- function GoToEndPage() {
- pageIndex = userCount - 1;
- searchUser( pageIndex, pageSize);
- }</span>
控制层代码如下:
- @RequestMapping("findContactsAjax")
- public @ResponseBody
- Map<String, Object> findContactAjax(String provinceId,String cityId,String pageIndex,String pageSize) {
- List<User> listUsers = userDao.selectUserByProvinceAndCity(provinceId, cityId,pageIndex,pageSize)
- }
- map.put("user", listUsers);
- return map;
- }
Dao层:
- List<User> selectUserByProvinceAndCity(@Param("provinceId") Integer provinceId, @Param("cityId") Integer cityId,
- @Param("pageIndex") Integer pageIndex,@Param("pageSize") Integer pageSize);
mapper文件:
- <select id="selectUserByProvinceAndCity" resultMap="BaseResultMap">
- SELECT *,
- (SELECT COUNT(*) FROM user_user_t
- province_id=#{provinceId}
- AND
- city_id=#{cityId}) AS userCount
- FROM user_user_t
- province_id=#{provinceId}
- AND
- city_id=#{cityId}
- LIMIT #{pageIndex},#{pageSize}
- </select>
User实体
- public class User {
- private Integer userId;
- private String userName;
- private Integer provinceId;
- private Integer cityId;
- private Integer userCount;//满足查询条件的用户数目,作为分页的依据
- }
- 《转:http://blog.csdn.net/gisredevelopment/article/details/39084945》