If you need a treecomponent which can load a tree structure dynamic based on the selected node, here’s a howto. This article adds a treecompontent to a simple struts jsp page and loads form details using ajax technology with Dojo.
Dojo has a tree component which does all the hard work for you. It can be fitted with a TreeLoadingController which can load JSON data from a servlet (and thus using ajax).
First create a jsp in which you want to display your tree. Insert the following imports:
<script type="text/javascript">
var djConfig = { isDebug: true };
</script>
<script language="JavaScript" src="/testapp/js/dojo.js">/*_*/</script>
<script type="text/javascript">
dojo.require("dojo.widget.Button");
dojo.require("dojo.event.*");
dojo.require("dojo.io.*");
dojo.require("dojo.widget.Tree");
dojo.require("dojo.widget.TreeNode");
dojo.require("dojo.widget.TreeSelector");
dojo.require("dojo.widget.TreeLoadingController");
</script>
In your document body create the treecomponent:
<div dojoType="TreeLoadingController" RPCUrl="/testapp/booksServlet" widgetId="treeController" DNDController="create"></div> <div dojoType="TreeSelector" widgetId="treeSelector"></div> <div dojoType="Tree" DNDMode="between" selector="treeSelector" widgetId="algOrgEenhedenTree" controller="treeController"> <div dojoType="TreeNode" title="Books" widgetId="root" objectId="" isFolder="true"></div>
In the TreeLoadingController the RPCUrl is the location of the servlet (or struts action) which returns a JSON collection of tree elements for the current node. The servlet is called with a parameter ‘data’ from which you can extract information about the selected node. Next you have to write your servlet wich returns a list of elements you want to display in the tree, for example books.
The component expects the result in the JSON format. I created a simple servlet which extracts the objectId of the current node and queries for it’s children. These are returned in the JSON format. Here’s the code that formats the result
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
// Get the data parameter sent by dojo
String data = request.getParameter("data");
// Gather the objectid from the data parameter string.
String OBJECTID = "\"objectId\":\"";
int start_idx = data.indexOf(OBJECTID) + OBJECTID.length();
int end_idx = data.indexOf('\"',start_idx);
String objectId = data.substring(start_idx, end_idx);
StringBuffer json = new StringBuffer();
while (i.hasNext()) {
// do stuff here to get your service objects
List books = service.getBooks(objectId);
for (Book book : books) {
String isfolder = book.getchildren().size() > 0 ? "true" : "false";
json.append("{title:\""+book.getTitle()+"\",isFolder:"+isfolder+",objectId:\""+book.getId()+"\"},");
}
// delete the last comma
json.deleteCharAt(json.length() -1);
json.append("]");
// get the servlet response object here..
response.setContentType("text/javascript");
PrintWriter writer = response.getWriter();
writer.println(json.toString());
writer.close();
}
Note: There are also JSON libraries for java available which you can use to build a json string. However for this small example using a StringBuffer will do. For example the result could look like:
[{title:"Ajax Books",isFolder:true,objectId:"101"},
{title:"JSP Books",isFolder:true,objectId:"110"},
{title:"Java 5 edition",isFolder:false,objectId:"102"}
]
When a user selects the plus-sign the servlet is automatically called through the TreeLoadingController and the tree is updated with the results from the servlet.
Now you have your tree, but you also need to do something with it. I used the selected node to query the details records from the server with dojo and fill a form with record details. In the javascript section of the jsp include the following code:
function init() {
var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
dojo.event.connect(treeSelector,'select','treeSelectFired');
<!-- Create a jsp form named detailform to populate, hide until details are selected -->
var detailform = document.getElementById('detailform');
detailform.style.visibility = 'hidden';
}
dojo.addOnLoad(init);
function treeSelectFired() {
<!-- get a reference to the treeSelector and get the selected node -->
var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
var treeNode = treeSelector.selectedNode;
var objectId = treeNode['objectId'];
retrieveFormDetails(objectId);
if (detailform.style.visibility == 'hidden') {
detailform.style.visibility = 'visible';
}
}
function retrieveFormDetails(objectId) {
dojo.io.bind({
url: "/testapp/bookDetailsServlet?objectId" + objectId,
load: function(type, data, evt) { updateFormData(data); },
error: function(type, data, evt) { displayError(type,data,evt); },
mimetype: "text/plain"
});
}
function updateFormData(data) {
var jsonData = data;
var jsonObject = eval('(' + jsonData + ')');
document.getElementById("bookid").value = jsonObject.detailform.bookid;
document.getElementById("bookname").value = jsonObject.detailform.bookname;
document.getElementById("bookprice").value = jsonObject.detailform.price;
}
function displayError(type, data, evt) {
alert('error callback!\ntype:'+type+'\ndata:'+data+'\nevt:'+evt);
}
The treeselectFired function is registered in the init function and called everytime a user click’s the plus-sign. The retrieveFormDetails functions is making a ajax call to the bookDetailsServlet and passed the objectId parameter. The javascript callback is handled in the updateFormData function which simply sets the form fields. This way our form is updated without refreshing the browser window. All what’s left is to write the bookDetailsServet. I ommitted this because it’s similair to the booksServlet.
This was one of my first attempts using ajax technology and I picked dojo from the list of available ajax toolkits and frameworks because I needed a treecomponent. Does anyone know a faster way to achieve the above? Note: It has to be struts/jsp and preferably portlet enabled.

May 3rd, 2007 at 10:27:20
[...] Original post by Albert Sikkema [...]
May 3rd, 2007 at 13:41:37
Hi Albert,
Glad you made it into the AJAX world
..
I think other java related ajax framework will perform comparable regarding the amount of code-lines needed to achieve something.
Maybe, writing you’r own AJAX component tree would be an option. You can choose to use to contruct the HTML on the server and append it in the right location in your page..This removes any JSON code. However, the code in the servlet becomes a little bit more complex but I prefer regular java code above javascript..
You can also make a side step and look into the Ruby on Rails AJAX api..(See: http://www.onlamp.com/pub/a/onlamp/2005/06/09/rails_ajax.html) It is really amazing how easy you can integrate ajax feature in your RoR page
regards,
-Tom
May 16th, 2007 at 08:56:37
hi albert,
“Use ajax treecompontent in jsp with DOJO”
if possible can u send me the full example . the code what u posted is not working for me because i am missing some classes.so kindly send me all what ever it require.
kindly send to this mail id tbommireddy@gmail.com
September 17th, 2007 at 10:33:07
hi albert,
if possible can you send me the full example project. the code what you posted is not completely because i am missing some variables and classes. so kindly send me all what ever it require.
kindly send to this mail id rs190774@aol.com
regards,
Ronny
August 27th, 2008 at 08:45:47
if possible can you send me the full example project. the code what you posted is not completely because i am missing some variables and classes. so kindly send me all what ever it require.
kindly send to this mail id vandana_mukheja@yahoo.co.in
Regards
Vandana
December 29th, 2008 at 21:50:19
Hi,
Can i get the full example project.
Thanks in advance.
Regards,
Satheesh
January 11th, 2009 at 21:29:28
[...] Use ajax treecompontent in jsp with DOJO [...]
January 27th, 2009 at 12:27:35
Hi,
Can i get the full example project.
Thanks in advance.
Regards,
angi
January 18th, 2010 at 18:03:23
hi albert,
if possible can you send me the full example project. the code what you posted is not completely because i am missing some variables and classes. so kindly send me all what ever it require.
kindly send to this mail id heamwant.bangwal@gmail.com
regards,
Heamwant
May 5th, 2010 at 02:17:01
Hello! adfeabb interesting adfeabb site!