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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值