如何使用 Spring MVC 控制器中的数据填充 ExtJS 树?

发布于 2024-10-30 07:25:43 字数 2748 浏览 2 评论 0原文

作为 ExtJS 的新手,我尝试将它与 Spring MVC 控制器一起使用。所以我的结构如下:tree.jsp 从 SomeController.java 获取 JSON 数据。我正在使用 Tiles 2 连接它们。

文件,而不是填充的

<script type="text/javascript">

if (Ext.BLANK_IMAGE_URL.substr(0,5) != 'data'){
    Ext.BLANK_IMAGE_URL = '/ext-3.3.1/resources/images/default/s.gif';
}

Ext.onReady(function(){

    var proxy = new Ext.data.HttpProxy({
        api: {
            read: 'jsonTree'
        }    
    });

    var treeLoader = new Ext.tree.TreeLoader({
        proxy: proxy
    });

    // shorthand
    var Tree = Ext.tree;

    var tree = new Tree.TreePanel({
        el:'tree-div', //we need to have a div in our html named this
        title: "Data Sources",
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        containerScroll: true,
        rootVisible: false,
        loader: treeLoader,

        root: {
            nodeType: 'async',
            text: 'Ext JS',
            draggable:false,
            id:'source'
        }
    });

    // render the tree
    tree.render();
});

当我向控制器

@Controller
@RequestMapping("/some")
public class SomeController {

private Logger log = LoggerFactory.getLogger(CountryReferenceBookController.class);
private static final String LIST_VIEW_KEY = "redirect:list.html";
@Autowired
private RestTemplate restTemplate;

@RequestMapping(value = "/jsonTree/{languageId:\\d+}")
public @ResponseBody Map<String, ? extends Object> getJsonTreeInfo(@PathVariable("languageId") Long languageId) {

    List treeList = new ArrayList<Map<String, Object>>();

    List<ReferenceBookTitleImpl> list = new ArrayList<ReferenceBookTitleImpl>();
    list = restTemplate.getForObject("http://localhost:8084/xcollector/restService/reference/list", list.getClass());


    for (ReferenceBookTitleImpl title : list) {
        String description = restTemplate.getForObject("http://localhost:8084/xcollector/restService/reference/title/" + title.getId() + "/content/" + languageId, String.class);

        //create a child node that is a leaf
        Map child = new HashMap();
        child.put("id", title.getId());
        child.put("text", description);
        child.put("checked", Boolean.FALSE);
        child.put("leaf", Boolean.TRUE);

        treeList.add(child);
    }

    //the spring mvc framework takes a hashmap as the model..... :| so in order to get the json array to the View, we need to put it in a HashMap
    Map modelMap = new HashMap();
    modelMap.put("JSON_OBJECT", treeList);

    log.info("jsonArray: " + treeList.toString());
    return modelMap;
}

发送 GET 响应时,我得到一个包含 json 数组的

树。我的代码有什么问题吗?

预先非常感谢, L。

As a newbie in ExtJS I'm trying to use it with Spring MVC Controller. So my structure is following: tree.jsp gets JSON data from SomeController.java. I'm using Tiles 2 to connect them.

tree.jsp

<script type="text/javascript">

if (Ext.BLANK_IMAGE_URL.substr(0,5) != 'data'){
    Ext.BLANK_IMAGE_URL = '/ext-3.3.1/resources/images/default/s.gif';
}

Ext.onReady(function(){

    var proxy = new Ext.data.HttpProxy({
        api: {
            read: 'jsonTree'
        }    
    });

    var treeLoader = new Ext.tree.TreeLoader({
        proxy: proxy
    });

    // shorthand
    var Tree = Ext.tree;

    var tree = new Tree.TreePanel({
        el:'tree-div', //we need to have a div in our html named this
        title: "Data Sources",
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        containerScroll: true,
        rootVisible: false,
        loader: treeLoader,

        root: {
            nodeType: 'async',
            text: 'Ext JS',
            draggable:false,
            id:'source'
        }
    });

    // render the tree
    tree.render();
});

SomeController.java

@Controller
@RequestMapping("/some")
public class SomeController {

private Logger log = LoggerFactory.getLogger(CountryReferenceBookController.class);
private static final String LIST_VIEW_KEY = "redirect:list.html";
@Autowired
private RestTemplate restTemplate;

@RequestMapping(value = "/jsonTree/{languageId:\\d+}")
public @ResponseBody Map<String, ? extends Object> getJsonTreeInfo(@PathVariable("languageId") Long languageId) {

    List treeList = new ArrayList<Map<String, Object>>();

    List<ReferenceBookTitleImpl> list = new ArrayList<ReferenceBookTitleImpl>();
    list = restTemplate.getForObject("http://localhost:8084/xcollector/restService/reference/list", list.getClass());


    for (ReferenceBookTitleImpl title : list) {
        String description = restTemplate.getForObject("http://localhost:8084/xcollector/restService/reference/title/" + title.getId() + "/content/" + languageId, String.class);

        //create a child node that is a leaf
        Map child = new HashMap();
        child.put("id", title.getId());
        child.put("text", description);
        child.put("checked", Boolean.FALSE);
        child.put("leaf", Boolean.TRUE);

        treeList.add(child);
    }

    //the spring mvc framework takes a hashmap as the model..... :| so in order to get the json array to the View, we need to put it in a HashMap
    Map modelMap = new HashMap();
    modelMap.put("JSON_OBJECT", treeList);

    log.info("jsonArray: " + treeList.toString());
    return modelMap;
}

}

When I send a GET response to the controller I get a file with json array instead of the populated tree. What is wrong with my code?

Thanks a lot in advance,
L.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迎风吟唱 2024-11-06 07:25:43

由于没有人问我,我决定自己回答我的问题。主要问题是对AJAX调用的理解错误。

如果要从 Spring MVC 控制器填充树面板,则必须实现两种方法:第一个返回树面板所在的视图,第二个返回填充树面板的数据。

我们来看一下例子:

首先我在项目中使用的是Tiles 2。因此,在包含图块的文件(templates.xml)中,我添加了以下图块:

<定义名称=“/tree”扩展=“defaultTemplate”>
    
     

负责处理 url http:////tree 上的请求的控制器有两个方法:

此方法返回 jsp 视图:

@RequestMapping(value = "/tree")
public ModelAndView getTreeView() {
    return new ModelAndView("/tree");
}

Next 方法返回json 数据:

@RequestMapping(value = "/tree/data", method=RequestMethod.POST)
public @ResponseBody List<Map<String, Object>>  getJsonTreeInfo() {

    List treeList = new ArrayList<Map<String, Object>>();

    List<FooImpl> list = new ArrayList<FooImpl>();
    list = restTemplate.getForObject("http://localhost:8084/<web-app>/restService/list", list.getClass());


    for (FooImpl foo : list) {
        String description = restTemplate.getForObject("http://localhost:8084/<web-app>/restService/title/" + foo.getId() + "/content/11", String.class);

        //create a child node that is a leaf
        Map child = new HashMap();
        child.put("id", foo.getId());
        child.put("text", description);
        child.put("leaf", Boolean.TRUE);

        treeList.add(child);
    }
    return treeList;
}

可能不清楚这个列表如何变成 json 数组。我有一个消息转换器,它正在完成所有转换工作。

JSP 端:

<script type="text/javascript">
    if (Ext.BLANK_IMAGE_URL.substr(0,5) != 'data'){
        Ext.BLANK_IMAGE_URL = '/ext-3.3.1/resources/images/default/s.gif';
    }

    // application main entry point
    Ext.onReady(function() { 

    // shorthand
    var Tree = Ext.tree;

    var tree = new Tree.TreePanel({
        useArrows: true,
        autoScroll: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        border: false,
        // auto create TreeLoader
        dataUrl: 'tree/data',

        root: {
            nodeType: 'async',
            text: 'List',
            draggable: false,
            id: 'src'
        }
    });

    // render the tree
    tree.render('tree-div');
    tree.getRootNode().expand();
});

</script>

<div id="tree-div"></div>

此行 dataUrl: 'tree/data' 将 POST 请求发送到第二个控制器的方法。它返回 json 数组。最后,树中填充了数据:)每个人都很高兴:)

我希望它对某人有帮助,因为我花了很多时间来找到这个解决方案。

享受你的工作:)

Since nobody had asked I decided to answer my question myself. The main problem was wrong understanding of AJAX call.

If you want to populate a tree panel from Spring MVC Controller you have to implement two methods: the first returns a view where the tree panel is located, the second returns a data which the tree panel is populated with.

Let's take a look at the example:

First of all, I use Tiles 2 in the project. So in a file with tiles (templates.xml) I added a following tile:

<definition name="/tree" extends="defaultTemplate">
    <put-attribute name="title" value="Tree" />
    <put-attribute name="content" value="/WEB-INF/jsp/tree.jsp"/> 
</definition>

The Controller which on charge of processing requests on an url http://<ip:port>/<web-app>/tree has two methods:

This method returns jsp view:

@RequestMapping(value = "/tree")
public ModelAndView getTreeView() {
    return new ModelAndView("/tree");
}

Next method returns json data:

@RequestMapping(value = "/tree/data", method=RequestMethod.POST)
public @ResponseBody List<Map<String, Object>>  getJsonTreeInfo() {

    List treeList = new ArrayList<Map<String, Object>>();

    List<FooImpl> list = new ArrayList<FooImpl>();
    list = restTemplate.getForObject("http://localhost:8084/<web-app>/restService/list", list.getClass());


    for (FooImpl foo : list) {
        String description = restTemplate.getForObject("http://localhost:8084/<web-app>/restService/title/" + foo.getId() + "/content/11", String.class);

        //create a child node that is a leaf
        Map child = new HashMap();
        child.put("id", foo.getId());
        child.put("text", description);
        child.put("leaf", Boolean.TRUE);

        treeList.add(child);
    }
    return treeList;
}

Could be unclear how this list becomes json array. I have a message converter which is doing all the job of converting.

JSP side:

<script type="text/javascript">
    if (Ext.BLANK_IMAGE_URL.substr(0,5) != 'data'){
        Ext.BLANK_IMAGE_URL = '/ext-3.3.1/resources/images/default/s.gif';
    }

    // application main entry point
    Ext.onReady(function() { 

    // shorthand
    var Tree = Ext.tree;

    var tree = new Tree.TreePanel({
        useArrows: true,
        autoScroll: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        border: false,
        // auto create TreeLoader
        dataUrl: 'tree/data',

        root: {
            nodeType: 'async',
            text: 'List',
            draggable: false,
            id: 'src'
        }
    });

    // render the tree
    tree.render('tree-div');
    tree.getRootNode().expand();
});

</script>

<div id="tree-div"></div>

This line dataUrl: 'tree/data' sends POST request to the second contoller's method. It returns the json array. Finally, the tree is popullated with data :) Everyone is happy :)

I hope it helps someone because I spent a lot of time to come to this solution.

Enjoy your job :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文