您的位置:首页 > 数据库 > Oracle

oracle分页(从jsp--->dao层,中间用json格式传递数据),数组的分页

2013-09-13 11:15 489 查看
声明:以下内容是在工作过程中总结,主要是供本人参考使用,可能不适用所有人,请谅解,谢谢

用oracle数据库的sql语句分页
---------------------------------------------------------html----分页部分----开始-----------------------------------------------------
<!--分页开始-->
    <div class="outline">

        <div class="pagination'>

            <div class="pagination">

                <!--第一页--> 
  
                <image src="images/firstpage.png" onclick="firstPage()"/>

                  <!--上一页--> 
  
                <image src="images/prepage.png"
onclick="prePage()"/>
                <div>第</div>

                <input id="page_goto" type="text" value="<%=pageCont.getPageNo() %>"  name="<%=pageCont.getPageNo()
%>"/>

                <div>页共</div>
                <div id="page_num'><span><%=pageCont.getTotalPages()%></span></div>
                <div>页</div>
                   <!--下一页--> 
  
                <image src="images/nextpage.png" onclick="nextPage()"/>  
                   <!--最后一页--> 
  
                <image src="images/lastpage.png" onclick="lastPage()"/>
                   <!--刷新--> 
  
                <image src="images/firstpage.png" onclick="refresh()"/>
            </div>
         </div>
    </div>

<!--分页结束-->
----------------------------------------------------------html----分页部分----开始-----------------------------------------------------

----------------------------------------------------------javascript----分页部分----开始-----------------------------------------------------
//封装分页js()
 var path = "xxx.action";    //要访问的action
var data = "";  //带条件查询的分页,data中加入查询条件
//第一页
function firstPage(path){
    var currentPage = parseInt($("#page_goto").val())

     if(currentPage == 1){
        $("#page_goto").val("1");

        alert(”已经第一页“);

    }else{
        queryData(path, 1, data);

    }

}
//上一页
function prePage(path){
    var prePage = parseInt($("#page_goto").val()) - 1;

    if(prePage < 1){
       $("#page_goto").val("1");
        alert("第一页");

        return;

    }else{
        queryData(path, prePage, data);

    }

}
 //下一页
function nextPage(path){
    var nextPage = parseInt($("#page_goto").val()) + 1;

    var pageSum = parseInt($("#page_num").text());

    if(nextPage > pageSum){
        $("#page_goto").val(pageSum);

        alert("最后一页");

        return;

    }else{
        queryData(path, nextPage, data);

    }

}
//最后一页
function lastPage(path){
    var pageSum = parseInt($("#page_num").text());

    var currtPage = parseInt($("#page_goto").val());

    if(pageSum == currtPage){
        $("#page_goto").val(pageSum);

        alert("已经最后一页");

    }else{
        queryData(path, pageSum, data);

    }

}

//输入页码,跳转到指定页数
//刷新
function refresh(path){
    var currtPage = parseInt($("#page_goto").val());

    var pageSum = parseInt($("#page_num").text());

    if((currtPage > 0) && (currtPage <= pageSum)){
        queryData(path, currtPage, data);

    }else{
        alert("请输入正确的页码");

    }

}

//查询数据
function queryData(){
    $.ajax({
        type:“POST”,
        url:path,

        data:"pageNo=" + pageNo+"&isajax=true" + data + "&time=" + new Date().getTime(),

        async:true,   //是否异步

        cache:false,  //是否缓存

        success:function(msg){
            var obj = eval("(" + msg + ")");

            //向页面中摄入值

            $("#page_goto").val(obj.pageNo);

            //动态生成tr

            createTr(obj);

        }

    });

}

//动态生成表单
function createTr(obj){
    //首先将当前列表移除

    $("#tbody tr").remove();

    for(var i=0; i<obj.list.length; i++ )

    var str = "<tr id= 'trid" +i+" '  onmouseover = 'mouseover("+i+")' onmouseout='mouseout(" +i+ ")'>";
    //注意:这里单引号和双引号之间的空格可能要删除 
    str += "<td><input type='checkbox' name='xuhao' value=' " + obj.list[i].hdt_id + " ' / >";
    str +="<td id= 'hdt_id" +i+" '>" + obj.list[i].name + "</td>";
    ……
     str
+="<td id= 'hdt_age" +i+" '>" + obj.list[i].age + "</td>";
    $("#tbody').append(str);

    }

    $("#page_num span").text(obj.totalPages);

}
//鼠标移到某一行上是添加样式
function mouseover(i){
    $(("#trid" + i)).css("background-color", "#535353");

}
//当鼠标移除该行时改变样式

function mouseover(i){
    $(("#trid" + i)).css("background-color", " ");

}

----------------------------------------------------------javascript----分页部分----结束-----------------------------------------------------

----------------------------------------------------------java类----PageModel----开始-----------------------------------------------------
package com.tools;
//注意这里用到json的jar包
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONConfig;
import org.apache.struts2.ServletActionContext;

/**
*封装分页信息
*lijunjun
*/
public class PageModel<T>{ //这里T是列表中展示vo对象

    //结果集

    private List<T> list;

    //查询记录数

    private int totalRecords;

    //每页多少条记录

    private int pageSize;

    //当前页码

    private int pageNo;

    //总页数

    private int totalPages;

    

    //生成get/set方法:如下总页数get方法比较特殊:如下

    //总页数get方法

    public int getTotalPages(){
        int size = (this.totalRecords + pageSize -1) / pageSize;

        return size;

    }

    public String getJsonStr(Object obj){
        JsonConfig jsonConfig = new JsonConfig();

        //这里是处理将日期转换成json格式的处理类

        jsonConfig.registerJsonValueProcessor(java.sql.TimeStamp.class, new DataJsonValueProcessor());

        JSONObject jsObject = JSONObject.fromObject(obj, jsonConfig);

        String msg = jsObject.toString();

        return msg;

    }

    public void sendJsonData(){
        try{
            HttpServletResponse response = ServletActionContext.getResponse();

            response.setContentType("text/html; charset=utf-8");

            PrintWriter out = response.getWriter();

            String msg = getJsonStr(this);

            out.print(msg);

            out.flush();

            out.close();

        }catch(IOException e){
            e.printStackTrace();
        }

    }
}

注意:需要导入json运行的jar包:

person类 :

import java.sql.Timestamp;
public class Person {
private int id;
private String usrname;
private Timestamp borthdate;            //如果这里是Date,则将工具类中的TimeStamp改为Date即可
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsrname() {
return usrname;
}
public void setUsrname(String usrname) {
this.usrname = usrname;
}
public Timestamp getBorthdate() {
return borthdate;
}
public void setBorthdate(Timestamp borthdate) {
this.borthdate = borthdate;
}
}

json日期格式转化工具类:

import java.sql.Timestamp;
import java.text.SimpleDateFormat;  
import java.util.Date;  

import net.sf.json.JsonConfig;  
import net.sf.json.processors.JsonValueProcessor;  

/**  
 * JSON日期格式转换 
 *  
*/  
public class DateJsonValueProcessor implements JsonValueProcessor  
{  
    private String format = "yyyy-MM-dd HH:mm:ss";  

    public DateJsonValueProcessor()  
    {   }  

    public DateJsonValueProcessor(String format)  
    {  
        this.format = format;  
    }  
//如果person类中的borthdate属性的类型为Date,则将该方法中的Timestamp改为Date即可
    public Object processArrayValue(Object value, JsonConfig jsonConfig)     
    {  

        String[] obj = {};  
        if (value instanceof Timestamp[])  
        {  
            SimpleDateFormat sf = new SimpleDateFormat(format);  
            Timestamp[] dates = (Timestamp[]) value;  
            obj = new String[dates.length];  
            for (int i = 0; i < dates.length; i++)  
            {  
                obj[i] = sf.format(dates[i]);  
            }  
        }  
        return obj;  
    }  

    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig)  
    {  

        if (value instanceof Date)  
        {  
            String str = new SimpleDateFormat(format).format((Date) value);  
            return str;  
        }  
        return value;  
    }  

    public String getFormat()  
    {  

        return format;  
    }  

    public void setFormat(String format)  
    {  

        this.format = format;  
    }  
}  

测试类:

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class test {
public static void main(String[] args) {
JsonConfig jsonConfig = new JsonConfig();  

Person p = new Person();
p.setId(1);
p.setUsrname("zhangsan");
p.setBorthdate(new Timestamp(System.currentTimeMillis()));

    jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor());  
    JSONObject jsonObj = JSONObject.fromObject(p, jsonConfig);  
 
System.out.println(jsonObj);
}
}

----------------------------------------------------------java类----PageModel----结束-----------------------------------------------------

----------------------------------------------------------action---开始-----------------------------------------------------
public class LsbzAction extends ActionSupport{
    private PageNodel<User> page;
    private boolean isajax;

    //get.set方法

    public String execute(){
        this.page = lsbzDao.selectUserList(pageNo, pageSize);

        if(isajax){
              
page.sendJsonData();
        }

     

    return success;

    }

}

----------------------------------------------------------action----结束-----------------------------------------------------

---------------------------------------------------------dao层分页sql语句----开始-----------------------------------------------------
public class LsbzImpl extends JdbcTemplate  implements LsbzDao{
    private PageModel<User>  page;

    public void setPage(PageModel<LsbzVo> page){
        this.page = page;

    }
    public PageModel<User> selectUserList(int pageNo, int pageSize) throws Exception{
         StringBuffer sbsql = new StringBuffer();
   sbsql.append("select id , username, age from ( ")
        .append(" select rownum rn, id , username, age from( ")
        .append(" select id, username, age  from test order by id ")
        .append(" ) where rownum <= " + (pageNo * pageSize))
        .append(" ) where rn > " + (pageNo - 1) * pageSize);
        //这里连接数据库是用spring的jdbcTemplate或者SimpleJdbcTemplate

        List<User> list = this.queryForList(sbSql.toString(), LsbzVo.class, String.valueOf(page*pageSize), String.valueOf((pageNo-1) * pageSize));

        this.page.setList(list);

        this.page.setTotalRecords(getTotalRecords());

        this.page.setPageSize(pageSize);

        this.page.setPageNo(pageNo);

        return this.page;

    } 

}
--------------------------------------------------------- dao层分页sql语句 ----结束-----------------------------------------------------

模拟数组分页:
---------------------------------------------------------数组分页----开始-----------------------------------------------------
package epurse.front.base; 

import java.util.ArrayList; 
import java.util.List; 

public class Pagination { 

private int maxPageLength = 10; // 页面最大记录数 
private int currentPage = 1;// 当前页面数 
private int maxLength = 0; // 总记录数 
private int maxPage = 1; // 总页数 
private List list; // 返回记录集 
private List resultList; // 目标记录集 

public List getResultList() { 
return resultList; 


public int getMaxPageLength() { 
return maxPageLength; 


public void setMaxPageLength(int maxPageLength) { 
this.maxPageLength = maxPageLength; 


public void setResultList(List resultList) { 
this.resultList = resultList; 


/** 
* @author wxj 
* @param resultList 
* @return maxLength 
*/ 
public int getMaxLength() { 
if(this.resultList==null||this.resultList.isEmpty()){ 
maxLength = 0; 

else{

maxLength = this.resultList.size(); 

return maxLength; 


public int getMaxPage() { 

int maxPage = getMaxLength() / this.maxPageLength; 
if (getMaxLength() % this.maxPageLength != 0) { 
maxPage = maxPage + 1; 

return maxPage; 


public List getList() { 
List list = new ArrayList(); 
if(this.resultList!=null&&!this.resultList.isEmpty()){ 
int length; 
if(getCurrentPage() == getMaxPage()) 

length = getMaxLength(); 

else 

length = getCurrentPage() * getMaxPageLength(); 
}

for (int i = (currentPage-1) * getMaxPageLength(); i < length; i++) { 
list.add(this.resultList.get(i)); 


return list; 


public int getCurrentPage() { 
return currentPage; 


public void setCurrentPage(int currentPage) { 
this.currentPage = currentPage; 


---------------------------------------------------------数组分页----结束-----------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  oracle 分页 json