基于mybatis ajax 分页的实现

Posted TT_DUL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于mybatis ajax 分页的实现相关的知识,希望对你有一定的参考价值。

博主这里的ajax 分页是基于上一篇 自定义标签的分页,其根本区别在于 ajax 分页 把自定义标签的内容 用 ajax 方式实现了,所以此ajax 分页也属于后台数据库分页,好了,看代码

1、说好了,在这里是基于上一篇文章的
所有的 service 层 和 dao 层的代码,包括page.java 基础类 和 mybatis 的拦截器实现,都是和上一篇文章一样的一样的,讲清楚以上,开始实现ajax 分页了

1、既然 是用ajax 访问,那么 control 层肯定是和普通方式不一样的了

     @RequestMapping(value="/testajax",method=RequestMethod.POST)
        public ResponseEntity<AjaxPageResponse> testajax( @ModelAttribute Branch branch ,
                 @RequestParam(required = false, defaultValue = "1") int pageNo,  
                  @RequestParam(required = false, defaultValue = "10") int pageSize, HttpServletRequest request) 

            Page page = Page.newBuilder(pageNo, pageSize, "/branchControl/testajax");
            Map<String, String> params = new HashMap<String, String>();

            if(null !=branch.getGeoCode())
                params.put("geoCode", branch.getGeoCode()+"");
            if(null !=branch.getTel())
                params.put("tel", branch.getTel()+"");

            page.setParams(params);

            List<Branch> mobileFindBranch = branchService.findDeptByGeoCode(branch,page);


            AjaxPageResponse model = new AjaxPageResponse();
            model.addObject("secbranch", mobileFindBranch); 


            if(!"".equalsIgnoreCase(branch.getTel()) && null !=branch.getTel())
                model.addObject("tel", branch.getTel());
            

            model.addObject("page", page);
            model.addObject("branch", branch);
            model.setPage(page);

            return new ResponseEntity<AjaxPageResponse>(model, HttpStatus.OK);
        

2、通过以上代码,可以看出 ,返回结果好像不太一样唉,对的,博主模仿 ModelAndView 类,建立 了一个新类 AjaxPageResponse

import java.util.HashMap;
import org.springframework.ui.ModelMap;


public class AjaxPageResponse 

    public Page page;

//  public T t;

    private ModelMap model;

    public AjaxPageResponse() 
    

    public ModelMap getModelMap() 
        if (this.model == null) 
            this.model = new ModelMap();
        
        return this.model;
    


    public AjaxPageResponse addObject(String attributeName, Object attributeValue) 
        getModelMap().addAttribute(attributeName, attributeValue);
        return this;
    

    public Page getPage() 
        return page;
    

    public void setPage(Page page) 
        this.page = page;
    

3、基础类 AjaxPageResultMap 及 AjaxPageModel

AjaxPageResultMap 类

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.core.Conventions;
import org.springframework.util.Assert;

public class AjaxPageResultMap extends LinkedHashMap<String, Object>



    public AjaxPageResultMap() 
    

    public AjaxPageResultMap(String attributeName, Object attributeValue) 
        addAttribute(attributeName, attributeValue);
    

    public AjaxPageResultMap(Object attributeValue) 
        addAttribute(attributeValue);
    

    public AjaxPageResultMap addAttribute(String attributeName, Object attributeValue) 
        Assert.notNull(attributeName, "Model attribute name must not be null");
        put(attributeName, attributeValue);
        return this;
    

    public AjaxPageResultMap addAttribute(Object attributeValue) 
        Assert.notNull(attributeValue, "Model object must not be null");
        if (attributeValue instanceof Collection && ((Collection) attributeValue).isEmpty()) 
            return this;
        
        return addAttribute(Conventions.getVariableName(attributeValue), attributeValue);
    


    public AjaxPageResultMap addAllAttributes(Collection<?> attributeValues) 
        if (attributeValues != null) 
            for (Object attributeValue : attributeValues) 
                addAttribute(attributeValue);
            
        
        return this;
    


    public AjaxPageResultMap addAllAttributes(Map<String, ?> attributes) 
        if (attributes != null) 
            putAll(attributes);
        
        return this;
    

    public boolean containsAttribute(String attributeName) 
        return containsKey(attributeName);
    



AjaxPageModel 类

import org.springframework.ui.ModelMap;

public class AjaxPageModel 

    private ModelMap model;

    public AjaxPageModel() 
    

    public ModelMap getModelMap() 
        if (this.model == null) 
            this.model = new ModelMap();
        
        return this.model;
    


    public AjaxPageModel addObject(String attributeName, Object attributeValue) 
        getModelMap().addAttribute(attributeName, attributeValue);
        return this;
    


4、然后当然就 是要把 上一篇博文的自定义标签实现的内容改为ajax 实现了

ajaxPageUtil.js 实现原理为 在原生ajax 函数上又加了一层,用来提取分页的属性值,并且显示分页的页面样式

function pageClick( pNo )  
                          if(!pNo)
                              pNo =pageObject.pageNo;
                          

                            var choosePageSize = $('#choosePageSize').find('option:selected').text(); 

                            var jsPost = function(action, values, valueLists)   
                                  var ajaxSearchParam=;

                                  for (var key in values)   
                                      ajaxSearchParam["" + key + ""]=values[key];
                                    
                                  for (var key2 in valueLists)   
                                    for (var index in valueLists[key2])   
                                      ajaxSearchParam["'" + key2 + "'"]=valueLists[key2][index];
                                      
                                    

                                  ajaxSearchParam.pageSize=choosePageSize;
                                  ajaxSearchParam.pageNo=pNo;

        //                        alert("ajaxSearchParam:"+JSON.stringify(ajaxSearchParam));

                                  var ajaxParm =;
                                  if(ajaxBodyObjectTmp.async)
                                  ajaxParm['async']=ajaxBodyObjectTmp.async;
                                  
                                  if(ajaxBodyObjectTmp.type)
                                  ajaxParm['type']=ajaxBodyObjectTmp.type;
                                  
                                  if(ajaxBodyObjectTmp.url)
                                  ajaxParm['url']=ajaxBodyObjectTmp.url;
                                  
                                  if(ajaxBodyObjectTmp.dataType)
                                  ajaxParm['dataType']=ajaxBodyObjectTmp.dataType;
                                  
                                  ajaxParm['data']=ajaxSearchParam;
                                  if(successFuction)
                                  ajaxParm['success']=successFuction;
                                  
                                  if(ajaxBodyObjectTmp.error)
                                      ajaxParm['error']=ajaxBodyObjectTmp.error;
                                  

                                  $.ajaxPage(ajaxParm);

                              
                            //发送POST  
                            jsPost(pageObject.searchUrl, paraJson, paraListJson);  
                  
                  function chPageSize(obj)
                     /* alert(obj.value); */
                     pageClick(1);

                  

            var ajaxBodyObjectTmp=null;
            var pageObject=null;
            var successFuction =null;
            $(function()

                function setPageTag(pageObject)

                    var  current =  pageObject.pageNo;  
                    var  begin = 1;  
                    var  end = pageObject.totalPage;  
                    var str="";
                    var nums=0;

                    str+="<div class='row-fluid'>";
                    str+="<div class='fyhpagediv' style='float: right;'>";

                    if (current!=1 && end!=0)  
                        nums =current-1;
                        str+="<span class='fyhfybk'><a href='javascript:void(0);' onclick='pageClick("+nums+")'>上一页</a>";
                    else 
                        str+="<span class='fyhfybk'><a href='javascript:void(0);'>上一页</a>";
                      

                    for(var i=0;i<pageObject.totalPage;i++)

                        if(i + 1 == current)
                            nums=i+1;
                            str+="<a href='#' class='pagebtn-red' >"+nums+"</a>";
                            else
                                if(i == 0 || i == 1 || i == 2 || i == 3 

                                        || i == current - 2 || i == current - 3 
                                        || i == current || i == current + 1 
                                        || i == Number(pageObject.totalPage) - 2 || i == Number(pageObject.totalPage) - 1)
                                    nums=Number(i)+1;
                                    str+="<a href='#' onclick='pageClick("+nums+")'>"+nums+"</a>";
                                else
                                    if(i == 4 && current > 7)
                                        str+="<a href='#'>...</a>";
                                    
                                    if(i == Number(pageObject.totalPage) - 3  && current < Number(pageObject.totalPage) - 4)
                                        str+="<a href='#'>...</a>";
                                    
                                
                            
                    


                    if (current<end && end!=0)
                        nums =current+1;
                        str+="<a href='javascript:void(0);' onclick='pageClick("+nums+")'>下一页</a></span>";
                    else
                        str+="<a href='javascript:void(0);'>下一页</a></span>";
                     

                    str+="</div>";

                    str+="<div class='fyhpagenum' style='float: right;'>";
                    str+="<span>每页</span>";
                    str+="<select id='choosePageSize' class='fyhpageselect' onchange='chPageSize(this)'>";
                    str+="<option ";
                    if(pageObject.pageSize==10)
                        str+="selected";
                    
                    str+=" >10</option>";
                    str+="<option ";
                    if(pageObject.pageSize==25)
                        str+="selected";
                    
                    str+=" >25</option>";
                    str+="<option ";
                    if(pageObject.pageSize==50)
                        str+="selected";
                    
                    str+=" >50</option>";
                    str+="</select>";
                    str+="<span>条</span>";
                    str+="<span>共"+pageObject.totalRecord+"条</span>";
                    str+="</div>";
                    str+="</div>";
                    str+="</div>";

                    $("#pageTag").html("");

                    $("#pageTag").append(str);
                



                //以下是用来增加ajax 分页的

                //jQuery 应用扩展
                jQuery.extend(

                      ajaxPage:function (ajaxBodyObject) 
                           ajaxBodyObjectTmp=ajaxBodyObject;
                           successFuction =ajaxBodyObject.success;

                           ajaxBodyObject.success=function(ajaxResult)
                               ajaxResult=eval("("+ajaxResult+")");

                                paraJson = ajaxResult.page.params;

                                paraListJson=ajaxResult.page.paramLists;

//                              alert("paraJson:"+paraJson);
//                              alert("paraListJson:"+paraListJson);
                                pageObject=ajaxResult.page;
                                setPageTag(pageObject);
                                successFuction(ajaxResult.modelMap);
                          

                          $.ajax(ajaxBodyObject);
                      
                );

                jQuery.extend(

                      reloadAjaxPage:function () 
                          pageClick();
                      
                );

            )

5、然后就是要在页面上使用了

首先,在页面中引入js 文件

<script type="text/javascript" src="../js/ajaxPageUtil.js"></script>

然后,写调用后台control 的方法,在这里 $.ajaxPage 的调用方法和 $.ajax 一模一样,然后,success 方法的 data 参数使用 和 control 最后的model 使用方法一样,直接data.secbranch 这样,就可以取出在control 中存入的值

function submit()
                //以下为应用获取数据提交
                var param=;
                param['geoCode']=$("#geoCode").val();
                param['tel']=$("#tel").val();
                $.ajaxPage(
                    async:false,
                    type:"POST", 
                    url:"$pageContext.request.contextPath/branchControl/testajax", 
                    dataType:"text",      
                    data:param,
                    success:function(data) 
                         var result =data.secbranch;
                         var str ="";
                         for(var i=0;i<result.length;i++)
                             str+="<tr class='odd gradeX ' >";
                             str+="<td >"+result[i].name+"</td>";
                             str+="<td>"+result[i].address+"</td>";
                             str+="<td >"+result[i].tel+"</td>";
                             str+="<td>"+result[i].businessScope+"</td>";
                             str+="<td>"+result[i].releaseTime+"</td>";
                             str+="<td>";
                             str+="<a title='查看' class=' fyhcz ' href='$pageContext.request.contextPath/branchControl/branch?branchId="+result[i].branchId+"'><i class='icon-search'></i></a>";
                             str+="<a title='编辑' class=' fyhcz ' href='$pageContext.request.contextPath/branchControl/forUpdate?branchId="+result[i].branchId+"'><i class='icon-edit'></i> </a>";
                             str+="<a title='删除' class=' fyhcz ' href='javascript:void(0);' onclick=delbranch("+result[i].branchId+",'"+result[i].name+"')><i class='icon-trash'></i></a>";
                             str+="</td>";
                             str+="</tr>";
                            
                         $("#wsltable").children("tbody").html("");
                         $("#wsltable").children("tbody").append(str);
                    ,       
                    error:function(e)
                        alert(e);
                      
                );
            

再然后,得在显示分页按钮的地方加入以下div

                                    <div class="row-fluid" id="pageTag">
                                    </div>

再然后就是赶紧跑起你的项目查看你的分页效果了

以上是关于基于mybatis ajax 分页的实现的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis源码分析自定义缓存分页的实现

MyBatis:分页的实现

MyBatis-Plus 实现分页的几种写法

MyBatis物理分页的代码实现

请高人讲解java ajax实现分页的思路

急求一个jsp+ajax实现分页的例子