ext 異步加載樹_2

附件中 是 整個項目 ,下載即可使用

1.需要建立數據庫和表結構 sql 和數據腳本 見上面

2.講項目放在TOMCat 可以直接運行

 

 

對於前臺接收json字符串 的一個思考(2010.05.23):

 

 

對於上面的例子,我們是使用 menu.jsp 來接收後臺的返回的json字符串

menu.jsp  的內容很簡單 2行

 

<%@ taglib prefix="s" uri="/struts-tags" %>
<s:property value="menuString" escape="false"/>

 

其中:

 

<s:property>標籤的escape屬性默認值爲true,即不解析html代碼,直接將其輸出。
如:novel.NTitle的值爲

<font color=red>邪門</font>

則<s:property value="#novel.NTitle">就直接輸出原值。若想讓標籤解析html標籤輸出:

邪門

則將escape設爲false

<s:property value="#novel.NTitle" escape="false"/>

 

 

這個例子中我們希望 輸出解析後的值,不想看到html標籤

 

 <action name="menus" class="cn.com.xinli.tree.action.QueryNodeAction">
            <result name="success">/menu.jsp</result>
  </action>

 

並且使用的是 <package name="struts2" extends="struts-default">

 

 

我們把 後臺的json字符串放在了 menuString 字符串中,

 

 

而extends="struts-default" 下面的action 都是頁面跳轉的意思

<result name="success">/menu.jsp</result>
的意思就是 action執行後 跳轉到 menu.jsp

 

tree.loader.dataUrl='http://localhost:9090/struts2/menus!loadTree.action?pid='+node.id

是ext 中的方法 他是用來接受json字符串的 ,首先看看 tree.loader.dataUrl 的源碼,可見

tree.loader.dataUrl 是一個ajax請求 接受返回結果,而loadTree.action 返回一個json字符串,剛好綁定在

 

menu.jsp 中,因此 tree.loader.dataUrl  得到了json字符串,由於是ajax請求,也不會引起頁面跳轉

 

 

Js代碼
  1. requestData : function(node, callback){   
  2.       if(this.fireEvent("beforeload"this, node, callback) !== false){   
  3.           this.transId = Ext.Ajax.request({   
  4.               method:this.requestMethod,   
  5.               url: this.dataUrl||this.url,   
  6.               success: this.handleResponse,   
  7.               failure: this.handleFailure,   
  8.               scope: this,   
  9.               argument: {callback: callback, node: node},   
  10.               params: this.getParams(node)   
  11.           });   
  12.       }else{   
  13.           // if the load is cancelled, make sure we notify   
  14.           // the node that we are done   
  15.           if(typeof callback == "function"){   
  16.               callback();   
  17.           }  
  requestData : function(node, callback){
        if(this.fireEvent("beforeload", this, node, callback) !== false){
            this.transId = Ext.Ajax.request({
                method:this.requestMethod,
                url: this.dataUrl||this.url,
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
                argument: {callback: callback, node: node},
                params: this.getParams(node)
            });
        }else{
            // if the load is cancelled, make sure we notify
            // the node that we are done
            if(typeof callback == "function"){
                callback();
            }

 

 

 

這種從後臺得到 json 字符串,傳遞到前臺一個Jsp頁面的做法有點 臃腫,比如我們還需要在 action中 使用json.jar

 

使用下面的方法 將一個對象轉化爲 json 字符串

 

 JSONArray jsonObject = JSONArray.fromObject(menus);
  menuString = jsonObject.toString();

 

其實 strtus2已經爲我們提供了action 返回 json字符串的支持,下面我們改造 以前手工得到json字符,用一個Jsp頁面來接受的例子,換成 使用strtus2 json 插件支持

 

步驟:

 

1.首先在以前的項目中加入

 

    jsonplugin-0.32.jar

 

2. 修改 後臺構造Json串的方法

 

 

Java代碼
  1. package cn.com.xinli.tree.action;   
  2. import java.util.List;   
  3. import javax.servlet.http.HttpServletRequest;   
  4. import org.apache.log4j.Logger;   
  5. import cn.com.xinli.tree.bean.FuctionTreeNode;   
  6. import cn.com.xinli.tree.dao.FuctionTreeDao;   
  7. import cn.com.xinli.tree.dao.impl.FuctionTreeDaoImpl;   
  8. public class QueryNodeAction extends BaseAction   
  9. {   
  10.     private Logger log=Logger.getLogger(QueryNodeAction.class);   
  11.     private String menuString;   
  12.     /*返回給前臺樹的Json 對象,使用struts2 json插件可以直接將這個對象轉換爲  
  13.      * json字符串  
  14.      * 需要在struts.xml中進行配置  
  15.      *   
  16.      * */  
  17.     private List<FuctionTreeNode> menusList;   
  18.        
  19.     public List<FuctionTreeNode> getMenusList() {   
  20.         return menusList;   
  21.     }   
  22.   
  23.     public void setMenusList(List<FuctionTreeNode> menusList) {   
  24.         this.menusList = menusList;   
  25.     }   
  26.   
  27.     public String getMenuString() {   
  28.         return menuString;   
  29.     }   
  30.   
  31.     public void setMenuString(String menuString) {   
  32.         this.menuString = menuString;   
  33.     }   
  34.   
  35.      
  36.     /*異步加載樹*/  
  37.     public String loadTree()   
  38.     {       
  39.           log.info("開始根據父親節點查找孩子節點");   
  40.           HttpServletRequest request=getRequest();   
  41.           String nodeId=request.getParameter("pid");   
  42.           log.info("父親節點的ID是:"+nodeId);   
  43.           FuctionTreeDao treeDao=new  FuctionTreeDaoImpl();   
  44.       try    
  45.       {   
  46.         menusList=treeDao.queryNodeById(nodeId);   
  47.          log.info("孩子結點的數目是:"+menusList.size());   
  48.         //以下三行代碼可以讓返回的JSON數據不包含需要過濾的字段   
  49.          /*  
  50.         JsonConfig config = new JsonConfig();  
  51.         //過濾cls屬性  
  52.         config.setExcludes( new String[]{"cls"});  
  53.         JSONArray jsonObject2 = JSONArray.fromObject(menus,config);  
  54.         */  
  55.         //JSONArray jsonObject = JSONArray.fromObject(menus);   
  56.       //    menuString = jsonObject.toString();   
  57.      
  58.        }   
  59.        catch (Exception e)    
  60.        {   
  61.             e.printStackTrace();   
  62.              
  63.        }   
  64.           
  65.      
  66.        return "success";   
  67.     }   
  68.     /*ajax 調用,返回json 字符串*/  
  69.     public String ajax()   
  70.     {   
  71.         //HttpServletResponse resp= getResponse();    
  72.         //resp.setContentType("application/json;charset=UTF-8");   
  73.         HttpServletRequest req= getRequest();    
  74.         try  
  75.         {   
  76.             System.out.println("從前臺Ajax請求參數是:"+req.getParameter("foo"));   
  77.             menuString="[{success:true,msg:'修改權限成功'}]";   
  78.             //resp.getWriter().write("{success:true,msg:'修改權限成功'}");   
  79.         }    
  80.         catch (Exception e)   
  81.         {   
  82.             // TODO Auto-generated catch block   
  83.             e.printStackTrace();   
  84.         }   
  85.            
  86.         return "aa";   
  87.     }   
  88.      
  89.        
  90.        
  91. }  
package cn.com.xinli.tree.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import cn.com.xinli.tree.bean.FuctionTreeNode;
import cn.com.xinli.tree.dao.FuctionTreeDao;
import cn.com.xinli.tree.dao.impl.FuctionTreeDaoImpl;
public class QueryNodeAction extends BaseAction
{
	private Logger log=Logger.getLogger(QueryNodeAction.class);
    private String menuString;
    /*返回給前臺樹的Json 對象,使用struts2 json插件可以直接將這個對象轉換爲
     * json字符串
     * 需要在struts.xml中進行配置
     * 
     * */
    private List<FuctionTreeNode> menusList;
    
    public List<FuctionTreeNode> getMenusList() {
		return menusList;
	}

	public void setMenusList(List<FuctionTreeNode> menusList) {
		this.menusList = menusList;
	}

	public String getMenuString() {
        return menuString;
    }

    public void setMenuString(String menuString) {
        this.menuString = menuString;
    }

  
    /*異步加載樹*/
    public String loadTree()
    {	 
    	  log.info("開始根據父親節點查找孩子節點");
	      HttpServletRequest request=getRequest();
	      String nodeId=request.getParameter("pid");
	      log.info("父親節點的ID是:"+nodeId);
	      FuctionTreeDao treeDao=new  FuctionTreeDaoImpl();
      try 
      {
      	menusList=treeDao.queryNodeById(nodeId);
    	 log.info("孩子結點的數目是:"+menusList.size());
   	  	//以下三行代碼可以讓返回的JSON數據不包含需要過濾的字段
    	 /*
    	JsonConfig config = new JsonConfig();
    	//過濾cls屬性
   	  	config.setExcludes( new String[]{"cls"});
   	  	JSONArray jsonObject2 = JSONArray.fromObject(menus,config);
   	  	*/
   	  	//JSONArray jsonObject = JSONArray.fromObject(menus);
   	  //	menuString = jsonObject.toString();
  
       }
       catch (Exception e) 
       {
       		e.printStackTrace();
          
       }
       
  
       return "success";
    }
    /*ajax 調用,返回json 字符串*/
    public String ajax()
    {
    	//HttpServletResponse resp= getResponse(); 
    	//resp.setContentType("application/json;charset=UTF-8");
    	HttpServletRequest req= getRequest(); 
    	try
    	{
    		System.out.println("從前臺Ajax請求參數是:"+req.getParameter("foo"));
    		menuString="[{success:true,msg:'修改權限成功'}]";
			//resp.getWriter().write("{success:true,msg:'修改權限成功'}");
		} 
    	catch (Exception e)
    	{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
    	return "aa";
    }
  
	
	
}

 

3 .修改 struts.xml 關鍵是 修改 packega 的 extends="json-default"

 

Xml代碼
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5.   
  6. <struts>  
  7.     <package name="struts2" extends="json-default">  
  8.         <action name="login" class="cn.com.xinli.tree.action.LoginAction">  
  9.             <result name="success">/result.jsp</result>  
  10.             <result name="input">/login2.jsp</result>  
  11.             <result name="error">/login2.jsp</result>  
  12.         </action>                                 
  13.          <action name="menus" class="cn.com.xinli.tree.action.QueryNodeAction">  
  14.             <result name="success" type="json">  
  15.                 <param name="root">menusList</param>  
  16.             </result>  
  17.                
  18.             <result name="aa" type="json">  
  19.                 <param name="root">menuString</param>  
  20.             </result>  
  21.         </action>  
  22.            
  23.          
  24.     </package>  
  25.        
  26. </struts>  
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="struts2" extends="json-default">
		<action name="login" class="cn.com.xinli.tree.action.LoginAction">
			<result name="success">/result.jsp</result>
			<result name="input">/login2.jsp</result>
			<result name="error">/login2.jsp</result>
		</action>                              
		 <action name="menus" class="cn.com.xinli.tree.action.QueryNodeAction">
            <result name="success" type="json">
            	<param name="root">menusList</param>
            </result>
            
            <result name="aa" type="json">
            	<param name="root">menuString</param>
            </result>
        </action>
        
      
	</package>
    
</struts>

 

 其中

 

<result name="success" type="json">
             <param name="root">menusList</param>
            </result>

 

代表 這個action的返回結果是 json字符串, 其中json串的 root節點 爲 menusList

 

如果你返回的對象 不需要那個屬性 可以這麼寫,則格式化  page 對象爲json字符串的時候

 

conditions,limit,start,success,objCondition 幾個屬性將被忽略

 

<param name="root">page</param>
    <param name="excludeProperties">
     conditions,limit,start,success,objCondition
    </param>

 

 相反的 如果只需要對象的 某個屬性轉化爲Json串 可以這麼寫

<result type="json">
    <param name="includeProperties">
     success,msg
    </param>
   </result>

 

附件中 extTreeJSON.rar 爲修改以後例子 ,其中 依賴的Lib 可以下載 以前的lib

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章