当前位置: 代码迷 >> Web前端 >> YUI2.8 兑现datasource datatable panel的综合应用,实时刷新数据
  详细解决方案

YUI2.8 兑现datasource datatable panel的综合应用,实时刷新数据

热度:242   发布时间:2012-11-09 10:18:47.0
YUI2.8 实现datasource datatable panel的综合应用,实时刷新数据

走了好长一段时间的弯路,终于实现了使用YUI2.8 实现datasource datatable panel的综合应用的例子,现在把它记录下来,作为以后的例子可以参考。

后台的程序

1、BaseStruts2Action的源代码:

package com.demo.action;

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

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("all")
public class BaseStruts2Action  extends ActionSupport {

	private static final long serialVersionUID = -7098181898244016914L;
	
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public void outJsonString(String str) {
		getResponse().setContentType("text/javascript;charset=UTF-8");
		outString(str);
	}

	public void outJson(Object obj) {
		String str = JSONObject.fromObject(obj).toString();
		System.out.println("str="+str);
		outJsonString(str);
	}

	public void outJsonArray(Object array) {
		outJsonString(JSONArray.fromObject(array).toString());		
	}

	public void outString(String str) {
		try {
			//禁止缓存json数据
			HttpServletResponse response = getResponse();
			response.setHeader("Pragma", "no-cache"); 
			response.setHeader("Cache-Control", "no-cache"); 
			response.setHeader("Expires", "0"); 
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write(str);
			writer.flush();
			writer.close();			
		} catch (IOException e) {
		}
	}

	public void outXMLString(String xmlStr) {
		getResponse().setContentType("application/xml;charset=UTF-8");
		outString(xmlStr);
	}
	
	protected String postData;

	protected int recordsReturned;
	protected int totalRecords;
	protected int startIndex;
	protected String sort;   
	protected String dir; 
	protected List records;
	protected int pageSize;
	
	public int getRecordsReturned() {
		return recordsReturned;
	}

	public void setRecordsReturned(int recordsReturned) {
		this.recordsReturned = recordsReturned;
	}

	public int getTotalRecords() {
		return totalRecords;
	}

	public void setTotalRecords(int totalRecords) {
		this.totalRecords = totalRecords;
	}

	public int getStartIndex() {
		return startIndex;
	}

	public void setStartIndex(int startIndex) {
		this.startIndex = startIndex;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public List getRecords() {
		return records;
	}

	public void setRecords(List records) {
		this.records = records;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public String getPostData() {
		return postData;
	}

	public void setPostData(String postData) {
		this.postData = postData;
	}

}

?

?

2、UserAction的源代码

package com.demo.action;

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

import net.sf.json.JSONObject;

import com.demo.model.Book;
import com.demo.model.InstBean;
import com.demo.model.User;
import com.demo.service.IBookService;
import com.demo.service.IUserService;
import com.demo.yuiutil.JSONResult;
import com.demo.yuiutil.YUIPagination;

@SuppressWarnings("all")
public class UserAction extends BaseStruts2Action{
	private IUserService userService;
	private User user;

	public String saveUser(){
		userService.saveUser(user);
		System.out.println("saveUser() has done.... ");
		return SUCCESS;
	}
	
	public void getUserList(){
		if( startIndex< 0 ){
			startIndex = 0;
		}
		if( pageSize<= 0 ){
			pageSize = 10;
		}
		System.out.println(" getUserList: startIndex="+startIndex+";pageSize="+pageSize);
		YUIPagination yuiPage = userService.getUserPagenation(startIndex, pageSize);			
		this.outJson(yuiPage);
	}
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
}

?

?

3、YUIPagination的源代码

package com.demo.yuiutil;

import java.util.List;
@SuppressWarnings("all")
public class YUIPagination {
	private int recordsReturned;
	private int totalRecords;
	private int startIndex;
	private String sort;   
	private String dir; 
	private List records;
	private int pageSize;
	
	public int getRecordsReturned() {
		return recordsReturned;
	}
	public void setRecordsReturned(int recordsReturned) {
		this.recordsReturned = recordsReturned;
	}
	public int getTotalRecords() {
		return totalRecords;
	}
	public void setTotalRecords(int totalRecords) {
		this.totalRecords = totalRecords;
	}
	public int getStartIndex() {
		return startIndex;
	}
	public void setStartIndex(int startIndex) {
		this.startIndex = startIndex;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getDir() {
		return dir;
	}
	public void setDir(String dir) {
		this.dir = dir;
	}
	public List getRecords() {
		return records;
	}
	public void setRecords(List records) {
		this.records = records;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
}

?

?

4、User ?IUserService? UserServiceImpl? ?IUserDao UserDaoImpl就是基本的java程序,我就不沾出来了。

?

5、struts的配置文件

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<include file="struts-default.xml"/>
	<constant name="struts.objectFactory" value="spring" />
	
	<package name="yuiapp" namespace="/yuiapp" extends="struts-default">
		<action name="user_*" method="{1}" class="com.demo.action.UserAction">
		    <result name="success">/pages/datatable/success.jsp</result>
		    <result name="input">/pages/datatable/addUser.jsp</result>
		</action>		
	</package>
	
</struts>

?

?

前台的程序

1、listUser.jsp (/yuiapp/WebRoot/pages/datatable/listUser.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%String sysPath =basePath+"appjs/yui/build"; %>
<%
    response.setHeader("Pragma","No-cache"); 
    response.setHeader("Cache-Control","no-cache"); 
    response.setDateHeader("Expires", 0); 
    response.flushBuffer();
    
    Cookie killMyCookie = new Cookie("mycookie", null);   
    killMyCookie.setMaxAge(0);   
    killMyCookie.setPath("/");   
    response.addCookie(killMyCookie);  
%> 
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta HTTP-EQUIV="Pragma" CONTENT="no-cache"> 
<meta HTTP-EQUIV="Cache-Control" CONTENT="no-cache"> 
<meta HTTP-EQUIV="Expires" CONTENT="0">

<title>list user</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="<%=sysPath %>/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="<%=sysPath %>/paginator/assets/skins/sam/paginator.css" />
<link rel="stylesheet" type="text/css" href="<%=sysPath %>/datatable/assets/skins/sam/datatable.css" />
<link rel="stylesheet" type="text/css" href="<%=sysPath %>/container/assets/skins/sam/container.css" />

<script type="text/javascript" src="<%=sysPath %>/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="<%=sysPath %>/connection/connection-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/json/json-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/element/element-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/paginator/paginator-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/datasource/datasource-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/datatable/datatable-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/dragdrop/dragdrop-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/container/container-min.js"></script>
<script type="text/javascript" src="<%=sysPath %>/editor/editor-min.js"></script>



<!--begin custom header content for this example-->
<style type="text/css"> 
/* custom styles for this example */
.yui-skin-sam .yui-dt-liner { white-space:nowrap; } 
</style>

</head>
<body class="yui-skin-sam">
<div class="exampleIntro">
	<p>实现的功能:从前端发送查询请求,后端处理请求,返回JSON数据,在前台展示</p>			
</div>

<input onclick="addUser();" type="button" value="增加" />
<div id="container">
   <div id="datatableId"></div>	
</div>
<div id="dt-pag-nav"></div>
<div id="addPanelId"></div>
<script type="text/javascript"> 
YuiUser = function() {   
	
    var myPaginator;	
    
	this.reloadDT = function(){
		myPaginator.fireEvent('changeRequest',myPaginator.getState({'page':myPaginator.getCurrentPage()}));
	};

	this.initDataTable = function(){
		// Column definitions
	    var myColumnDefs = [
	            {key:"id"},
	            {key:"loginName"},
	            {key:"userName"}
	    ];
	    
	    var myDataSource = new YAHOO.util.DataSource("http://127.0.0.1:8080/yuiapp/yuiapp/user_getUserList.action?");
	    myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
	    myDataSource.responseSchema = {
	        resultsList: "records",
	        fields: [
	            {key:"id"},
	            {key:"loginName"},
	            {key:"userName"}        
	        ],
	        metaFields: {
	            totalRecords: "totalRecords" // Access to value in the server response
	        }
	    };
	    
	    // DataTable configuration
	    myPaginator = new YAHOO.widget.Paginator( {   
	    	firstPageLinkLabel : "第一页", 
            lastPageLinkLabel : "最后页", 
            previousPageLinkLabel:"上一页",
            nextPageLinkLabel:"下一页",
            rowsPerPage:15,
	        containers : ["dt-pag-nav"],
	        pageReportTemplate : "查询到{totalRecords}条记录"
		});
	    var myConfigs = {
    		MSG_EMPTY : "没有信息",
	    	MSG_ERROR : "查询错误",
	    	MSG_LOADING : "正在查询,请稍候...",
	        initialRequest: "startIndex=0&pageSize=10",
	        dynamicData: true,
	        paginator: myPaginator
	    };
	    
	    // DataTable instance
	    
	    var myDataTable = new YAHOO.widget.DataTable("datatableId", 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;
	    };
	};// end for initDataTable()	

};

yuiUser = new YuiUser();
yuiUser.initDataTable();

var addPanel;
function addUser(){	
	addPanelId.style.display="";
	addPanel = new YAHOO.widget.Panel("addPanelId", {width:"400px",height:"200px",modal:true,visible:true, draggable:true, close:true } );
	addPanel.setHeader("增加用户");
	addPanel.setBody("<iframe src='addUser.jsp' style='width:350px;height:150px;' frameborder='0' id='addPanelFrame' name='addPanelFrame'></iframe>");
	addPanel.render();
	//addPanel.center();
}

function closeBox(){
	alert("操作成功!");
	addPanel.hide();
	addPanelId.style.display="none";
	//addPanel.destroy();
	//updateNewsBox.destroy();
	yuiUser.reloadDT();
}

</script>

</body>
</html>

?

?

2、addUser.jsp (/yuiapp/WebRoot/pages/datatable/addUser.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %> 
<!DOCTYPE html PUBLIC "-//W 3C //DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>add_user</title> 
</head>
<body>
<s:form action="/yuiapp/user_saveUser.action" method="post"> 
    <s:textfield name="user.loginName" label="登录名"/>
    <s:textfield name="user.userName" label="姓名"/> 
    <s:submit/>
</s:form>
</body>
</html>

?

3、success.jsp(/yuiapp/WebRoot/pages/datatable/success.jsp)

?

<%@ page language="java" pageEncoding="utf-8" contentType="text/html;charset=utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<center>操作成功</center>
<script type="text/javascript">
		window.parent.closeBox();
</script>
</body>

?

  相关解决方案