JQuery Tree using JSON as dataset


Following things are required :
JS : jquery.js, jquery.jstree.js, jquery.cookie.js, jquery.hotkeys.js
JAR : json-1.0.0.jar.

Index.jsp

<%-- 
    Document   : index
    Created on : Feb 26, 2011, 12:19:10 PM
    Author     : TaherT
--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Tree</title>
         <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/jquery.jstree.js"></script>
	<script type="text/javascript" src="js/jquery.cookie.js"></script>
	<script type="text/javascript" src="js/jquery.hotkeys.js"></script>
    </head>
    <body>
        <div id="treeMsg" style="width: 50%;display:none" align="center"></div>
        <div id="jsTreeComponent" class="demo" style="width: 50%"></div>

	<script>
	$(function () {
		$("#jsTreeComponent").jstree({
			"json_data" : {
                            "ajax" : {
                                "url" : '<%=request.getContextPath()%>/GetJSON'
                            }
			},
                        "themes" : {
                            "theme" : "apple",
                            "dots" : true,
                            "icons" : true
                        },
			"plugins" : [ "themes", "json_data", "ui","checkbox" ]
		});
                $("#jsTreeComponent").bind("select_node.jstree", function (e, data) {
                });
	});
	</script>
    </body>
</html>


DataClass.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taher.jquery.tree;

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

/**
 *
 * @author TaherT
 */
public class DataClass {

    List<Technology> techList = new ArrayList<Technology>();

    public List<Technology> getTechList() {
        if(techList.isEmpty()){            
            techList.add(new Technology(1, 0,"Java"));
            techList.add(new Technology(0, 1,"J2SE"));
            techList.add(new Technology(0, 1,"J2EE"));
            techList.add(new Technology(0, 1,"J2ME"));
            techList.add(new Technology(1, 0,".NET"));
            techList.add(new Technology(0, 1,"Sliverlight"));
            techList.add(new Technology(1, 0,"PHP"));
            techList.add(new Technology(0, 1,"Zend"));
            techList.add(new Technology(0, 1,"Cake"));
        }
        return techList;
    }
    

    public void setTechList(List<Technology> techList) {
        this.techList = techList;
    }

    class Technology {

        private int Id;
        private int pId;
        private String techName;

        public int getId() {
            return Id;
        }

        public void setId(int Id) {
            this.Id = Id;
        }

        public int getpId() {
            return pId;
        }

        public void setpId(int pId) {
            this.pId = pId;
        }

        public String getTechName() {
            return techName;
        }

        public void setTechName(String techName) {
            this.techName = techName;
        }

        public Technology(int Id, int pId, String techName) {
            this.Id = Id;
            this.pId = pId;
            this.techName = techName;
        }
    }
}

GetJSON.java is servlet which returns the JSON string

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taher.jquery.tree;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author TaherT
 */
@WebServlet(name = "GetJSON", urlPatterns = {"/GetJSON"})
public class GetJSON extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            DataClass dataClass = new DataClass();
            List<DataClass.Technology> listCPV = dataClass.getTechList();
            JSONArray jSONArray = new JSONArray();
            for(int i=0; i<listCPV.size();){
                JSONObject jSONObject = new JSONObject();                
                jSONObject.put("state","open");
                jSONObject.put("data",listCPV.get(i).getTechName());

                JSONObject jsonAttr = new JSONObject();                
                jsonAttr.put("techname", listCPV.get(i).getTechName());
                jSONObject.put("attr", jsonAttr);
                jsonAttr = null;

                if(listCPV.get(i+1).getId()==0){
                    JSONArray jsonChildarray = new JSONArray();

                    while(listCPV.get(i+1).getId()==0){
                        i++;
                        JSONObject child = new JSONObject();
                        child.put("data",listCPV.get(i).getTechName());

                        JSONObject jsonChildAttr = new JSONObject();                        
                        jsonChildAttr.put("techname", listCPV.get(i).getTechName());
                        child.put("attr", jsonChildAttr);
                        jsonChildAttr = null;

                        jsonChildarray.put(child);
                        child=null;

                        if(listCPV.size()==(i+1)){
                            break;
                        }
                    }
                    jSONObject.put("children", jsonChildarray);
                    jSONArray.put(jSONObject);
                    jSONObject=null;
                }
                i++;
            }
            System.out.println(jSONArray);
            out.print(jSONArray);
            jSONArray=null;
        }catch(Exception e){
            System.out.println(e);
        }
        finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

Output :

About these ads
This entry was posted in JQuery, Servlet. Bookmark the permalink.

4 Responses to JQuery Tree using JSON as dataset

  1. mohit jain says:

    i just want to do same thing along with lazy loading means on click of parent node only , hit the controller and reterive the child’s and so on.

  2. Jeff says:

    How would you alter the servlet to allow nested items in the tree?

  3. khanh4all says:

    Thanks so much for your article. It’s amazing!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s