开发者

How to populate ExtJS Tree with data from Spring MVC Controller?

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.开发者_JS百科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.


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜