yunshichen

我相信人生是值得活的,尽管人在一生中必须遭受痛苦,卑劣,残酷,不幸和死亡的折磨,我依然深信如此.但我认为人生不一定要有意义,只是对一些人而言,他们可以使人生有意义. ---J 赫胥黎

YUI datatable 源码

Java:



package org.diegochen.yuitut.base.controller;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.diegochen.webmvc.dao.PaginateHolder;
import org.diegochen.webmvc.ex.BusinessException;
import org.diegochen.webmvc.web.WebUtil;
import org.diegochen.yuitut.base.pojo.Account;
import org.diegochen.yuitut.base.pojo.State;
import org.diegochen.yuitut.base.service.IAccountService;
import org.diegochen.yuitut.base.service.IStateService;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class AccountController extends MultiActionController{
    Logger logger 
= Logger.getLogger(AccountController.class);
    
private static final int rowsPerPage=10;
    
private IAccountService accountService;
    
private IStateService stateService;
    
private int sleepTime=2000;
        
    
public void setSleepTime(int sleepTime) {
        
this.sleepTime = sleepTime;
    }
    
public void setStateService(IStateService stateService) {
        
this.stateService = stateService;
    }
    
public void setAccountService(IAccountService accountService) {
        
this.accountService = accountService;
    }
    
public ModelAndView main(HttpServletRequest request, HttpServletResponse response) throws Exception {
        
return new ModelAndView("/yuitut/accountList");
    }
    
public ModelAndView paginationList(HttpServletRequest request, HttpServletResponse response) throws Exception {

        PaginateHolder ph 
= accountService.retrievePaginateList(WebUtil.getRecordStartIndex(request, rowsPerPage),rowsPerPage, null);
        List
<State> stateList = stateService.retrieveStateList(null);
        StringBuffer json 
= new StringBuffer(200);
        
        json.append(
"{\"recordReturned\":");
        json.append(rowsPerPage);
        json.append(
",\"totalRecords\":");
        json.append(ph.getCount());
        json.append(
",\"startIndex\":");
        json.append(ph.getStartIndex());
        json.append(
",\"sort\":null");
        json.append(
",\"dir\":\"asc\"");
        json.append(
",\"pageSize\":");
        json.append(rowsPerPage);
        json.append(
",\"records\":[");
        
        List
<Account> accList = ph.getDataList();
        Account account;
        
for(int i=0,s=accList.size();i<s;i++){
            
if(i>0){
                json.append(
",");
            }
            account
=accList.get(i);
            json.append(
"{\"id\":");
            json.append(account.getId());
            json.append(
",\"name\":");
            json.append(
"\""+account.getName()+"\"");
            json.append(
",\"stateName\":");
            json.append(
"\""+getNameFromId(account.getStateId(),stateList)+"\"}");            
        }
        json.append(
"]}");
        
if(logger.isDebugEnabled()){
            logger.debug(json);
        }
        
        PrintWriter pw 
= response.getWriter();
        pw.print(json);
        
        
return null;
    }
    
public ModelAndView createAccount(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Thread.sleep(sleepTime);
        String name
=request.getParameter("name");
        String state
=request.getParameter("stateName");        
        
        List
<State> stateList = stateService.retrieveStateList(null);        
        Long stateId
=getIdFromName(state, stateList);
        
        PrintWriter pw 
= response.getWriter();
        StringBuffer json 
= new StringBuffer(100);
        
if(name==null || stateId==null){
            printResponse(pw,
"no""Your account name or state name is not correct.");
            
return null;
        }
        
try{
            Account acc 
= new Account();
            acc.setName(name);
            acc.setStateId(stateId);
            accountService.createAccount(acc);
        }
catch(BusinessException be){
            
//logger.debug(be);
            printResponse(pw,"no", be.getMessage());
            
return null;            
        }
catch(Exception ex){
            logger.debug(ex);
            printResponse(pw,
"no""Service error when creating new account.");
            
return null;            
        }
        
        printResponse(pw, 
"yes""Account have been created successfully.");        
        
        
return null;
    }
    
    
public ModelAndView updateAccount(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Thread.sleep(sleepTime);
        String id
=request.getParameter("id");
        String name
=request.getParameter("name");
        String state
=request.getParameter("stateName");        
        
        List
<State> stateList = stateService.retrieveStateList(null);        
        Long stateId
=getIdFromName(state, stateList);
        
        PrintWriter pw 
= response.getWriter();
        StringBuffer json 
= new StringBuffer(100);
        
if(name==null || stateId==null){
            printResponse(pw,
"no""Your account name or state name is not correct.");
            
return null;
        }
        
try{
            Account acc 
= new Account();
            acc.setId(Long.valueOf(id));
            acc.setName(name);
            acc.setStateId(stateId);
            accountService.updateAccount(acc);
        }
catch(BusinessException be){
            
//logger.debug(be);
            printResponse(pw,"no", be.getMessage());
            
return null;            
        }
catch(Exception ex){
            logger.debug(ex);
            printResponse(pw,
"no""Service error when creating new account.");
            
return null;            
        }
        
        printResponse(pw, 
"yes""Account have been updated successfully.");        
        
        
return null;
    }
    
    
private Long getIdFromName(String name,List<State> alist){
        
if(name==null || name.trim().equals("")){
            
return null;
        }    
        State state
=null;
        
for(int i=0,s=alist.size();i<s;i++){
            state
=alist.get(i);
            
if(state.getName().equals(name)){
                
return state.getId();
            }
        }
        
return null;
    }
    
    
private String getNameFromId(Long id,List<State> alist){
        
if(id==null){
            
return "";
        }
        State state
=null;
        
for(int i=0,s=alist.size();i<s;i++){
            state
= alist.get(i);
            
if(state.getId().longValue()==id.longValue()){
                
return state.getName();
            }
        }
        
return "";
    }
    
private void printResponse(PrintWriter pw,String flag,String msg){
        StringBuffer json 
= new StringBuffer(100);
        json.append(
"{");
        json.append(
"flag:'");
        json.append(flag);        
        json.append(
"',msg:'");
        json.append(msg);        
        json.append(
"'}");
        pw.print(json);        
    }
}

相关datalist的jsp代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>


    
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Account Management</title>

<style type="text/css">
/*margin and padding on body element
  can introduce errors in determining
  element position and are not recommended;
  we turn them off as a foundation for YUI
  CSS treatments. 
*/
body 
{
    margin
:0;
    padding
:0;
}
</style>

<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/yui2.8/build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/yui2.8/build/autocomplete/assets/skins/sam/autocomplete.css" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/yui2.8/build/paginator/assets/skins/sam/paginator.css" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/yui2.8/build/datatable/assets/skins/sam/datatable.css" />    
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/yui2.8/build/container/assets/skins/sam/container.css" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/yui2.8/build/resize/assets/skins/sam/resize.css" />


<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/connection/connection-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/json/json-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/element/element-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/paginator/paginator-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/datatable/datatable-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/animation/animation-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/autocomplete/autocomplete-min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/utilities/utilities.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/container/container.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/yui2.8/build/resize/resize.js"></script>


<!--begin custom header content for this example-->
<style type="text/css">
#myAutoComplete 
{
    width
:150px; /* set width here or else widget will expand to fit its container */
    padding-bottom
:2em;
}


</style>


<!--end custom header content for this example-->

</head>

<body class="yui-skin-sam">


<h1>Account List</h1>

<div id="dynamicdata"></div>    

</div>
<br/>

<!--BEGIN SOURCE CODE FOR EXAMPLE =============================== -->

<br/><br/>
<hr/>
<br/><br/>
<h1>Create Account</h1>
&nbsp;&nbsp;<div id="responseSpan1"></div>
<table border="0">
<tr><td>Name:</td><td><input type="text" id="nameCreate" size="20"/></td></tr>
<tr align="top"><td>State:</td><td><div id="myAutoComplete">
    
<input id="myInput" type="text">
    
<div id="myContainer"></div>
</div></td></tr>
<tr><td colspan="2" align="center"><input type="button" value="Create" onclick="createAccount();"/></td></tr>
</table>
<br/>

<br/>

<br/>
<div id="waitpic" style="display:none"><img src="<%= request.getContextPath()%>/img/waiting1.gif"/></div>

<div id="examplecontainer">
    
<div id="resizablepanel">
        
<div class="hd">Account Update</div>
        
<div class="bd">
            
<h1>Update Account</h1>
            
&nbsp;&nbsp;<div id="responseSpan2"></div>
            
<table border="0">
            
<tr><td>Name:</td><td><input type="text" id="nameUpdate" size="20"/></td></tr>
            
<tr valign="top"><td>State:</td><td><div id="myAutoComplete1">
                
<input id="myInput1" type="text">
                
<div id="myContainer1"></div>
            
</div></td></tr>
            
</table><br/>
            
<center><input type="button" value="Update" onclick="updateAccount();"/></center>
            
<input type="hidden" id="hiddenId" value=""/>
        
</div>
        
<div class="ft"></div>
    
</div>
</div>


</body>
</html>


<script type="text/javascript">
var arrayStates=[
    
"Albamas"
    ,
"Alaska"
    ,
"Florida"
];

    
var myColumnDefs = [ // sortable:true enables sorting
                         {key:"id", label:"ID", sortable:true},
                         {key:
"name", label:"Name", sortable:true},
                         {key:
"stateName", label:"State", sortable:true}
                     ];
    
// DataSource instance
    //var myDataSource = new YAHOO.util.DataSource("assets/php/json_proxy.php?");
    var myDataSource = new YAHOO.util.DataSource("<%=request.getContextPath()%>/account/paginationList.do?");
    myDataSource.responseType 
= YAHOO.util.DataSource.TYPE_JSON;
    myDataSource.responseSchema 
= {
        resultsList: 
"records",
        fields: [
            {key:
"id", parser:"number"},
            {key:
"name"},
            {key:
"stateName"}
        ],
        metaFields: {
            totalRecords: 
"totalRecords" // Access to value in the server response
        }
    };
    
    
// DataTable configuration
    var myConfigs = {
        initialRequest: 
"sort=id&dir=asc&startIndex=0&results=15"// Initial request for first page of data
        dynamicData: true// Enables dynamic server-driven data
        sortedBy : {key:"id", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
        paginator: new YAHOO.widget.Paginator({ rowsPerPage:15 }) // Enables pagination 
    };
    
    
// DataTable instance
    var myDataTable = new YAHOO.widget.DataTable("dynamicdata", myColumnDefs, myDataSource, myConfigs);
    
// Update totalRecords on the fly with value from server
    /**
    myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
        oPayload.totalRecords = oResponse.meta.totalRecords;
        return oPayload;
    }
    *
*/
    myDataTable.subscribe(
"rowMouseoverEvent", myDataTable.onEventHighlightRow);
    myDataTable.subscribe(
"rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
    myDataTable.subscribe(
"rowClickEvent", myDataTable.onEventSelectRow);
    myDataTable.subscribe(
"cellDblclickEvent", showUpdateForm);

    
// Use a LocalDataSource
    var oDS = new YAHOO.util.LocalDataSource(arrayStates);
    
// Optional to define fields for single-dimensional array
    oDS.responseSchema = {fields : ["state"]};

    
// Instantiate the AutoComplete
    var oAC1 = new YAHOO.widget.AutoComplete("myInput""myContainer", oDS);
    
/**
    oAC1.formatResult = function(oResultData, sQuery, sResultMatch) {
        if(oResultData.thumbnail_url) {
            img = "<img src=\""+ oResultData.thumbnail_url + "\">";
        }
        else {
            img = "<span class=\"img\"><span class=\"imgtext\">N/A</span></span>";
        }
        return "<div class=\"result\">" + img + " <span class=\"name\">" + sResultMatch + "</span></div>";
    };
    *
*/
    
    oAC1.prehighlightClassName 
= "yui-ac-prehighlight";
    oAC1.useShadow 
= true;
    

function updateTable(){
    myDataTable.getDataSource().sendRequest(
            myDataTable._request,
            myDataTable.onDataReturnInitializeTable,
            myDataTable
    );
 };

var responseDivId="";
var handleSuccess = function(o){ 
    hidePic();
    
if(o.responseText !== undefined){ 
        
var oResult=eval('(' + o.responseText + ')');
        
var sHtml;
        
if(oResult.flag==='no'){
            sHtml
="<font color='#FF0000'>"+oResult.msg+"</font>";
        } 
else{
            sHtml
="<font color='#008000'>"+oResult.msg+"</font>";
        }
        setDivInnerHtml(responseDivId,sHtml);
        updateTable();
    }
}
var handleFailure = function(o){
    
var sHtml="";
    
if(o.responseText !== undefined){
        sHtml 
= "<li>Transaction id: " + o.tId + "</li>";
        sHtml 
+= "<li>HTTP status: " + o.status + "</li>";
        sHtml 
+= "<li>Status code message: " + o.statusText + "</li>";
    }
    setDivInnerHtml(responseDivId,sHtml);
}

var callback =
{
  success:handleSuccess
  ,failure: handleFailure
};

function clearResponseMessage(){
    
var odiv = document.getElementById("responseSpan");
    odiv.innerHTML
="";
}
function showPic(){
    
var odiv = document.getElementById("waitpic");
    odiv.style.display
="";
}
function hidePic(){
    
var odiv = document.getElementById("waitpic");
    odiv.style.display
="none";
}

function createAccount(){
    responseDivId
="responseSpan1";
    
var sUrl="<%=request.getContextPath()%>/account/createAccount.do";    
    
var name=document.getElementById("nameCreate").value;
    
var stateName=document.getElementById("myInput").value;
    sUrl
+="?name="+name+"&stateName="+stateName;

    
var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
    
    showPic();
}
function updateAccount(){
    responseDivId
="responseSpan2";
    
var sUrl="<%=request.getContextPath()%>/account/updateAccount.do";    
    
var id=document.getElementById("hiddenId").value;
    
var name=document.getElementById("nameUpdate").value;
    
var stateName=document.getElementById("myInput1").value;
    sUrl
+="?name="+name+"&stateName="+stateName+"&id="+id;

    
var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); 
    
    showPic();
}

//Init update form.
var panel = new YAHOO.widget.Panel("resizablepanel", {
    draggable: 
true,
    width: 
"300px",
    height: 
"300px",
    left:
"500px",
    top:
"200px",
    autofillheight: 
"body"// default value, specified here to highlight its use in the example
    constraintoviewport:true,
    context: [
"showbtn""tl""bl"]
});


//Init autocomplete2
var oAC2 = new YAHOO.widget.AutoComplete("myInput1""myContainer1", oDS);

panel.render();
panel.hide();

function showUpdateForm(oEvent,oTarget){
    setDivInnerHtml(
"responseSpan1","");
    setDivInnerHtml(
"responseSpan2","");
    
var oRow=myDataTable.getSelectedTrEls()[0]; 
    
var childs=oRow.childNodes;
    
//Set update form value.
    if(window.event){
        setInputValue(
"hiddenId",childs[0].innerText);
        setInputValue(
"nameUpdate",childs[1].innerText);
        setInputValue(
"myInput1",childs[2].innerText);
    }
else{
        setInputValue(
"hiddenId",childs[0].textContent);
        setInputValue(
"nameUpdate",childs[1].textContent);
        setInputValue(
"myInput1",childs[2].textContent);
    }
    panel.show();
}


function setInputValue(sId,sValue){
    
var oInput = document.getElementById(sId);
    oInput.value
=sValue;
}
function setDivInnerHtml(sId,sHtml){
    
var oDiv = document.getElementById(sId);
    oDiv.innerHTML
=sHtml;
}

</script>



posted on 2009-10-30 13:49 Chenyunshi 阅读(800) 评论(0)  编辑 收藏 引用 所属分类: Yahoo YUI

只有注册用户登录后才能发表评论。
<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(7)

随笔分类

随笔档案

文章分类

相册

搜索

最新评论

阅读排行榜

评论排行榜