当前位置: 代码迷 >> JavaScript >> struts2调整ExtJS实现动态树加载
  详细解决方案

struts2调整ExtJS实现动态树加载

热度:695   发布时间:2012-10-06 17:34:01.0
struts2整合ExtJS实现动态树加载

?在研究ExtJS Tree动态构建时,按照ExtJS推进的方法是通过TreeLoader加载数据,加载的数据的格式是JSON。在ExtJS的例子check-tree.html中,直接利用后端的check-nodes.json来构建,但是在实际的工程中,有很多是根据不确定的数据内容来构建Tree的。

??? 在Java开发的Web中利用Struts实现后端的servlet,可以提供相应的json格式,实现ExtJS Tree的动态构建。在网上搜索相应的技术文章是,发现利用jsp作为中间转换的例子,url:http://www.blogjava.net/usherlight/archive/2008/02/19/180590.html,觉得不是很理想,在struts2中引入了plugin的机制,有现成的struts-json-plugin包,如何利用action直接通过Ext.Tree.TreeLoader直接加载Tree的数据,在上述文章中,指出:

?"最近尝试用extjs来展示树状菜单。着实花了一番功夫。树状菜单的菜单项需要动态加载,而目前版本的extjs中只支持JSON格式的数据。查了一些资料,决定使用struts2的json-plugin。首先按照例子做了一个,但是结果就是不成功,界面上只出来了一个js中生成的root节点,不能加载从后台生成的数据。研究后发现是数据格式有问题。使用json-plugin生成的数据格式如下:
{"cls":"folder","id":10,"leaf":false,"children":[{"cls":"file","id":11,"leaf":true,"children":null,"text":"S600"},{"cls":"file","id":12,"leaf":true,"children":null,"text":"SLK200"}],"text":"Benz"}
而extjs需要的数据格式如下:
[{"cls":"folder","id":10,"leaf":false,"children":[{"cls":"file","id":11,"leaf":true,"children":null,"text":"S600"},{"cls":"file","id":12,"leaf":true,"children":null,"text":"SLK200"}],"text":"Benz"}]
区别很小,就只相差最外面的两个方括号。但是少了这两个方括号,在json中,含义迥然不同,前者表示一个对象,而后者表示一个数组。而extjs中 tree的dataloader需要的数据必须是一个数组。而这样的数据格式是json-plugin自动生成的,无法改变。所以,我最后放弃了json -plugin,转而使用json-lib来解决这个问题。"

在struts-json-plugin中返回的数据的确有这个问题,经过仔细分析,在struts-json-plugin的配置中是可以解决这个问题的,通过wrapPrefix和wrapSuffix设置,可以解决上面的问题,struts config文件中的设置如下:

Xml代码 复制代码?收藏代码
  1. <package?name="test"?extends="json-default"?>??
  2. ????????????<action?name="menu"?class="com.struts2.action.Menu">??
  3. ????????<result?name="success"?type="json">??
  4. ????????????<param?name="excludeNullProperties">true</param>??
  5. ????????????<param?name="noCache">true</param>??
  6. ????????????<param?name="wrapPrefix">[</param>??
  7. ????????????<param?name="wrapSuffix">]</param>??
  8. ????????</result>??
  9. ????</action>??
  10. </package>??
	<package name="test" extends="json-default" >
				<action name="menu" class="com.struts2.action.Menu">
			<result name="success" type="json">
				<param name="excludeNullProperties">true</param>
				<param name="noCache">true</param>
				<param name="wrapPrefix">[</param>
				<param name="wrapSuffix">]</param>
			</result>
		</action>
	</package>

?action的实现类Menu的代码如下:

Java代码 复制代码?收藏代码
  1. package?com.struts2.action; ??
  2. ??
  3. import?java.util.ArrayList; ??
  4. import?java.util.List; ??
  5. ??
  6. public?class?Menu?{ ??
  7. ????private?int?id; ??
  8. ????private?String?text; ??
  9. ????private?boolean?leaf; ??
  10. ????private?String?cls; ??
  11. ????private?List<Menu>?children; ??
  12. ??
  13. ????public?String?execute()?throws?Exception?{ ??
  14. ????????//?TODO?Auto-generated?method?stub ??
  15. ????????this.id?=1; ??
  16. ????????this.text="text"; ??
  17. ????????this.leaf=false; ??
  18. ????????this.cls?="cls"; ??
  19. ????????this.children?=?new?ArrayList<Menu>(); ??
  20. ????????Menu?benz?=?new?Menu(); ??
  21. ????????benz.setText("Benz"); ??
  22. ????????benz.setCls("folder"); ??
  23. ????????benz.setLeaf(true); ??
  24. ????????benz.setId(10); ??
  25. ??
  26. ????????this.children.add(benz); ??
  27. ??
  28. ????????return?"success"; ??
  29. ????} ??
  30. ????public?int?getId()?{ ??
  31. ????????return?id; ??
  32. ????} ??
  33. ????public?void?setId(int?id)?{ ??
  34. ????????this.id?=?id; ??
  35. ????} ??
  36. ????public?String?getText()?{ ??
  37. ????????return?text; ??
  38. ????} ??
  39. ????public?void?setText(String?text)?{ ??
  40. ????????this.text?=?text; ??
  41. ????} ??
  42. ????public?boolean?isLeaf()?{ ??
  43. ????????return?leaf; ??
  44. ????} ??
  45. ????public?void?setLeaf(boolean?leaf)?{ ??
  46. ????????this.leaf?=?leaf; ??
  47. ????} ??
  48. ????public?String?getCls()?{ ??
  49. ????????return?cls; ??
  50. ????} ??
  51. ????public?void?setCls(String?cls)?{ ??
  52. ????????this.cls?=?cls; ??
  53. ????} ??
  54. ????public?List<Menu>?getChildren()?{ ??
  55. ????????return?children; ??
  56. ????} ??
  57. ????public?void?setChildren(List<Menu>?children)?{ ??
  58. ????????this.children?=?children; ??
  59. ????} ??
  60. }??
package com.struts2.action;

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

public class Menu {
    private int id;
    private String text;
    private boolean leaf;
    private String cls;
    private List<Menu> children;

	public String execute() throws Exception {
		// TODO Auto-generated method stub
		this.id =1;
		this.text="text";
		this.leaf=false;
		this.cls ="cls";
		this.children = new ArrayList<Menu>();
        Menu benz = new Menu();
        benz.setText("Benz");
        benz.setCls("folder");
        benz.setLeaf(true);
        benz.setId(10);

		this.children.add(benz);

		return "success";
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public boolean isLeaf() {
		return leaf;
	}
	public void setLeaf(boolean leaf) {
		this.leaf = leaf;
	}
	public String getCls() {
		return cls;
	}
	public void setCls(String cls) {
		this.cls = cls;
	}
	public List<Menu> getChildren() {
		return children;
	}
	public void setChildren(List<Menu> children) {
		this.children = children;
	}
}

?

利用ExtJS自带的例子check-tree.js,把原来的dataUrl修改为自己实现的struts的Url:

Js代码 复制代码?收藏代码
  1. /*! ?
  2. ?*?Ext?JS?Library?3.2.0 ?
  3. ?*?Copyright(c)?2006-2010?Ext?JS,?Inc. ?
  4. ?*?licensing@extjs.com ?
  5. ?*?http://www.extjs.com/license ?
  6. ?*/??
  7. ??
  8. Ext.onReady(function(){ ??
  9. ????var?tree?=?new?Ext.tree.TreePanel({ ??
  10. ????????renderTo:'tree-div', ??
  11. ????????title:?'My?Task?List', ??
  12. ????????height:?300, ??
  13. ????????width:?400, ??
  14. ????????useArrows:true, ??
  15. ????????autoScroll:true, ??
  16. ????????animate:true, ??
  17. ????????enableDD:true, ??
  18. ????????containerScroll:?true, ??
  19. ????????rootVisible:?false, ??
  20. ????????frame:?true, ??
  21. ????????root:?{ ??
  22. ????????????nodeType:?'async'??
  23. ????????}, ??
  24. ??
  25. ????????//?auto?create?TreeLoader ??
  26. ????????dataUrl:?'http://localhost:8080/Stock3th/menu.action', ??
  27. ??
  28. ????????listeners:?{ ??
  29. ????????????'checkchange':?function(node,?checked){ ??
  30. ????????????????if(checked){ ??
  31. ????????????????????node.getUI().addClass('complete'); ??
  32. ????????????????}else{ ??
  33. ????????????????????node.getUI().removeClass('complete'); ??
  34. ????????????????} ??
  35. ????????????} ??
  36. ????????}, ??
  37. ??
  38. ????????buttons:?[{ ??
  39. ????????????text:?'Get?Completed?Tasks', ??
  40. ????????????handler:?function(){ ??
  41. ????????????????var?msg?=?'',?selNodes?=?tree.getChecked(); ??
  42. ????????????????Ext.each(selNodes,?function(node){ ??
  43. ????????????????????if(msg.length?>?0){ ??
  44. ????????????????????????msg?+=?',?'; ??
  45. ????????????????????} ??
  46. ????????????????????msg?+=?node.text; ??
  47. ????????????????}); ??
  48. ????????????????Ext.Msg.show({ ??
  49. ????????????????????title:?'Completed?Tasks', ??
  50. ????????????????????msg:?msg.length?>?0???msg?:?'None', ??
  51. ????????????????????icon:?Ext.Msg.INFO, ??
  52. ????????????????????minWidth:?200, ??
  53. ????????????????????buttons:?Ext.Msg.OK ??
  54. ????????????????}); ??
  55. ????????????} ??
  56. ????????}] ??
  57. ????}); ??
  58. ??
  59. ????tree.getRootNode().expand(true); ??
  60. });??
/*!
 * Ext JS Library 3.2.0
 * Copyright(c) 2006-2010 Ext JS, Inc.
 * licensing@extjs.com
 * http://www.extjs.com/license
 */

Ext.onReady(function(){
    var tree = new Ext.tree.TreePanel({
        renderTo:'tree-div',
        title: 'My Task List',
        height: 300,
        width: 400,
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        containerScroll: true,
        rootVisible: false,
        frame: true,
        root: {
            nodeType: 'async'
        },

        // auto create TreeLoader
        dataUrl: 'http://localhost:8080/Stock3th/menu.action',

        listeners: {
            'checkchange': function(node, checked){
                if(checked){
                    node.getUI().addClass('complete');
                }else{
                    node.getUI().removeClass('complete');
                }
            }
        },

        buttons: [{
            text: 'Get Completed Tasks',
            handler: function(){
                var msg = '', selNodes = tree.getChecked();
                Ext.each(selNodes, function(node){
                    if(msg.length > 0){
                        msg += ', ';
                    }
                    msg += node.text;
                });
                Ext.Msg.show({
                    title: 'Completed Tasks',
                    msg: msg.length > 0 ? msg : 'None',
                    icon: Ext.Msg.INFO,
                    minWidth: 200,
                    buttons: Ext.Msg.OK
                });
            }
        }]
    });

    tree.getRootNode().expand(true);
});

?则可以生成所需要的Tree了。我用的各种资源的版本为:ExtJS3.2.0,Struts2.2.1,所需要的支持jar配置文件pom.xml如下:

Xml代码 复制代码?收藏代码
  1. <?xml?version="1.0"?encoding="UTF-8"?>??
  2. ????<!-- ??
  3. ????????/*?*?$Id:?pom.xml?821140?2009-10-02?19:46:07Z?wesw?$?*?*?Licensed?to ??
  4. ????????the?Apache?Software?Foundation?(ASF)?under?one?*?or?more?contributor ??
  5. ????????license?agreements.?See?the?NOTICE?file?*?distributed?with?this?work ??
  6. ????????for?additional?information?*?regarding?copyright?ownership.?The?ASF ??
  7. ????????licenses?this?file?*?to?you?under?the?Apache?License,?Version?2.0?(the ??
  8. ????????*?"License");?you?may?not?use?this?file?except?in?compliance?*?with ??
  9. ????????the?License.?You?may?obtain?a?copy?of?the?License?at?*?* ??
  10. ????????http://www.apache.org/licenses/LICENSE-2.0?*?*?Unless?required?by ??
  11. ????????applicable?law?or?agreed?to?in?writing,?*?software?distributed?under ??
  12. ????????the?License?is?distributed?on?an?*?"AS?IS"?BASIS,?WITHOUT?WARRANTIES ??
  13. ????????OR?CONDITIONS?OF?ANY?*?KIND,?either?express?or?implied.?See?the ??
  14. ????????License?for?the?*?specific?language?governing?permissions?and ??
  15. ????????limitations?*?under?the?License.?*/ ??
  16. ????-->??
  17. <project?xmlns="http://maven.apache.org/POM/4.0.0"?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??
  18. ????xsi:schemaLocation="http://maven.apache.org/POM/4.0.0?http://maven.apache.org/maven-v4_0_0.xsd">??
  19. ????<modelVersion>4.0.0</modelVersion>??
  20. ??
  21. ????<artifactId>org.tkxing.stock</artifactId>??
  22. ????<groupId>stock3th</groupId>??
  23. ????<version>3.0</version>??
  24. ??
  25. ????<properties>??
  26. ????????<struts2-version>2.2.1</struts2-version>??
  27. ????</properties>??
  28. ??
  29. ????<dependencies>??
  30. ????????<dependency>??
  31. ????????????<groupId>org.apache.struts</groupId>??
  32. ????????????<artifactId>struts2-core</artifactId>??
  33. ????????????<version>2.2.1</version>??
  34. ????????</dependency>??
  35. ????????<dependency>??
  36. ????????????<groupId>org.apache.struts</groupId>??
  37. ????????????<artifactId>struts2-json-plugin</artifactId>??
  38. ????????????<version>2.2.1</version>??
  39. ????????</dependency>??
  40. ????????<dependency>??
  41. ????????????<groupId>commons-logging</groupId>??
  42. ????????????<artifactId>commons-logging</artifactId>??
  43. ????????????<version>1.1.1</version>??
  44. ????????</dependency>??
  45. ????????<dependency>??
  46. ????????????<groupId>org.apache</groupId>??
  47. ????????????<artifactId>log4j</artifactId>??
  48. ????????????<version>2.1.8</version>??
  49. ????????</dependency>??
  50. ????????<dependency>??
  51. ????????????<groupId>javassist</groupId>??
  52. ????????????<artifactId>javassist</artifactId>??
  53. ????????????<version>3.9.0.GA</version>??
  54. ????????</dependency>??
  55. ??
  56. ????????<dependency>??
  57. ????????????<groupId>commons-lang</groupId>??
  58. ????????????<artifactId>commons-lang</artifactId>??
  59. ????????????<version>2.4</version>??
  60. ????????</dependency>??
  61. ??
  62. ????????<dependency>??
  63. ????????????<groupId>commons-collections</groupId>??
  64. ????????????<artifactId>commons-collections</artifactId>??
  65. ????????????<version>3.2.1</version>??
  66. ????????</dependency>??
  67. ??
  68. ????????<dependency>??
  69. ????????????<groupId>commons-beanutils</groupId>??
  70. ????????????<artifactId>commons-beanutils</artifactId>??
  71. ????????????<version>1.7.0</version>??
  72. ????????</dependency>??
  73. ??
  74. ????????<dependency>??
  75. ????????????<groupId>net.sf.ezmorph</groupId>??
  76. ????????????<artifactId>ezmorph</artifactId>??
  77. ????????????<version>1.0.6</version>??
  78. ????????</dependency>??
  79. ??
  80. ????</dependencies>??
  81. </project>??
1 楼 天朗java 2012-01-13  
楼主不行啊,我在Action里写了个

String jsonStr="{" +
"'text': 'To Do'," +
"'cls': 'folder'," +
"'expanded': true," +
"'children': [" +
"{" +
"'text': 'Go jogging'," +
"'leaf': true," +
"'checked': true" +
" }," +
"{" +
"'text': 'Take a nap'," +
"'leaf': true," +
"'checked': false" +
"}," +
" {" +
"'text': 'Climb Everest'," +
"'leaf': true," +
"'checked': false" +
"}" +
"]" +
"}" ;
返回的: ["{'text': 'To Do','cls': 'folder','expanded': true,'children': [{'text': 'Go jogging','leaf': true,'checked': true },{'text': 'Take a nap','leaf': true,'checked': false}, {'text': 'Climb Everest','leaf': true,'checked': false}]}"]  怎么去掉双引号 ……  谢谢!
  相关解决方案