Loading Tree of java_easyui System

Source: Internet
Author: User

Loading Tree of java_easyui System
I. Introduction

Implement the initialization of the three trees, and focus on the dynamic loading of trees using ajax.

1. Use the class attribute to initialize the tree.

2. Use javascript to initialize the tree

3. Use ajax to dynamically load trees

4. Use ajax to initialize the tree and expand all nodes of the tree

II:



3. Implementation steps
1. Use class initialization tree

A) define the tree-like html document, specify the class = "easyui-tree" attribute, and add the desired attributes, methods, and events to data-options.


 
 
  • Folder
    • Sub Folder 1
      • File 11
      • File 12
      • File 13
    • File 2
    • File 3
  • File21


2. Use javascript to initialize the tree

A) define a ul label for Tree placement


 
 

    B) use javascript for initialization


    $ (Function () {// use javascript to initialize $ ('# tt2 '). tree ({data: [{"id": 1, "text": "Folder1", "iconCls": "icon-save", "children ": [{"text": "File1", "checked": true}, {"text": "Books", "state": "open", "attributes ": {"url": "/demo/book/abc", "price": 100}, "children": [{"text": "PhotoShop", "checked ": true },{ "id": 8, "text": "Sub Bookds", "state": "closed"}]}, {"text ": "Ages", "state": "closed", "children": [{"text": "Java" },{ "text ": "C #"}]});

    3. Use ajax to dynamically load trees

    A) Preparations

    I. create a database, store Tree information, use hibernate to automatically create here, add a general idea here, when I write the TreeDTO and its configuration file, and start the program, nothing will be given I created a table and found the cause of the crash. It was originally in applicationContext. the hibernate ing file is not loaded into mappingResource in xml: Figure




    Ii. data manually added in the database: Figure




    Iii. Java Bean: TreeDTO code used to generate and save Tree information


    package com.chy.ssh.business.bean;import java.io.Serializable;@SuppressWarnings("serial")public class TreeDTO implements Serializable{private String id;private String pid;private String text;private String url;private int seq;public TreeDTO() {super();}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getPid() {return pid;}public void setPid(String pid) {this.pid = pid;}public String getText() {return text;}public void setText(String text) {this.text = text;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public int getSeq() {return seq;}public void setSeq(int seq) {this.seq = seq;}}


    Iv. EasyUITree code used to construct a Json string and return it to the foreground


    Package com. chy. ssh. business. bean. modal; import java. io. serializable; import java. util. map; @ SuppressWarnings ("serial") public class EasyUITree implements Serializable {private String id; private String text; private Boolean checked = false; private Map
     
      
    Attributes; private String state = "open"; // The getXXX () setXXX () method is omitted}
     


    B) main steps:

    I. Front-end: Only one URL request will automatically upload the id to the back-end. We don't need to get it again and use other code to change parameters to request the back-end -- code:


    $ (Function () {// asynchronously dynamic loading tree $ ('# tt3 '). tree ({url: 'treeaction _ treeLoad. action ', lines: true, checkbox: true ,});});

    Ii. backend: query records based on sent IDs and process strings (the input id is null, and the query here is to be judged)

    Code in TreeAction:


    Public void treeLoad () {// set of storage trees queried from the database, such as id, parent class id, text, etc. You can expand the List by yourself.
     
      
    List = treeService. getTreesByParentId (id); // The tree attributes displayed on the foreground, such as id, state, text, and checked.
      
       
    EList = new ArrayList
       
        
    (); If (list. size ()! = 0) {for (TreeDTO t: list) {EasyUITree e = new EasyUITree (); e. setId (t. getId (); e. setText (t. getText (); Map
        
         
    Attributes = new HashMap
         
          
    (); Attributes. put ("url", t. getUrl (); e. setAttributes (attributes); int count = treeService. countChildrens (t. getId (); if (count> 0) {// note the state attribute. When it is open, it indicates that the node is a folder and will be displayed as a folder. // when it is closed, it indicates the node. is a specific file node and is not displayed as a folder. E. setState ("closed");} eList. add (e) ;}} id = null; // convert the set containing information used to display the tree into json format and upload it to the foreground. WriteJson. pwObj (eList );}
         
        
       
      
     

    Code in the underlying DAO:


    public List
     
       getTreesByParentId(String id) {StringBuffer hql = new StringBuffer();if(id == null || "".equals(id)){hql.append("from TreeDTO t where t.pid is null ");}else{hql.append("from TreeDTO t where t.pid = '"+id+"' ");}List
      
        list = new ArrayList
       
        ();try {list = this.getHibernateTemplate().find(hql.toString());} catch (DataAccessException e) {e.printStackTrace();}return list;}
       
      
     


    Iii. Use the json tool to process the query and processed result sets into json strings and upload them to the front-end for display.

    Implementation of WriteJson. pwObj (eList:


    package com.chy.ssh.utils;import java.io.IOException;import java.io.PrintWriter;import java.io.StringWriter;import org.apache.struts2.ServletActionContext;import org.codehaus.jackson.JsonFactory;import org.codehaus.jackson.JsonGenerator;import org.codehaus.jackson.map.ObjectMapper;public class WriteJson {public static String getJson(Object o) {StringWriter sw = new StringWriter();try {ObjectMapper om = new ObjectMapper();JsonGenerator jg = new JsonFactory().createJsonGenerator(sw);om.writeValue(jg, o);jg.close();} catch (IOException e) {e.printStackTrace();}return sw.toString();}public static void pwObj(Object obj){try {PrintWriter pw = ServletActionContext.getResponse().getWriter();pw.print(getJson(obj));pw.flush();pw.close();} catch (IOException e) {e.printStackTrace();}}}

    4. Load a tree at a time using ajax

    With the previous things, it is easy to add an onLoadSuccess event to the initialization tree. The Code is as follows:

    // Asynchronously and dynamically load the tree $ ('# tt3 '). tree ({url: 'treeaction _ treeLoad. action ', lines: true, checkbox: true, onLoadSuccess: function (node, data) {console.info (node); console.info (data); var t = $ (this ); if (data) {$ (data ). each (function (index, d) {if (this. state = 'closed ') {t. tree ('pandall ');}});}}});

    Iv. Source Code supplement
    1. tree. jsp:

    <% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %>My JSP 'tree. jsp 'starting page
     
     
     
     
     
     <Script type = "text/javascript"> $ (function () {// use javascript to initialize $ ('# tt2 '). tree ({data: [{"id": 1, "text": "Folder1", "iconCls": "icon-save", "children ": [{"text": "File1", "checked": true}, {"text": "Books", "state": "open", "attributes ": {"url": "/demo/book/abc", "price": 100}, "children": [{"text": "PhotoShop", "checked ": true },{ "id": 8, "text": "Sub Bookds", "state": "closed"}]}, {"text ": "Ages", "state": "closed", "children": [{"text": "Java" },{ "text ": "C #"}]}); // asynchronously dynamically loads the tree $ ('# tt3 '). tree ({url: 'treeaction _ treeLoad. action ', lines: true, checkbox: true, onLoadSuccess: function (node, data) {console.info (node); console.info (data); var t = $ (this ); if (data) {$ (data ). each (function (index, d) {if (this. state = 'closed ') {t. tree ('pandall') ;}}}}}) ;}}); </script>Initial tree by class:
     
     
    • Folder
      • Sub Folder 1
        • File 11
        • File 12
        • File 13
      • File 2
      • File 3
    • File21

    Initial tree by javascript:

      Dynamic load tree:

        2. TreeAction:
        Package com. chy. ssh. web. action; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import com. chy. ssh. business. bean. treeDTO; import com. chy. ssh. business. bean. modal. easyUITree; import com. chy. ssh. business. service. treeService; import com. chy. ssh. utils. writeJson; import com. opensymphony. xwork2.ActionSupport; public class TreeAction extends ActionSupport {private static final long serialVersionUID = 1L; private TreeService treeService; private String id; public void treeLoad () {// The set of stored trees queried from the database, such as id, parent class id, text, etc. You can extend the List by yourself.
         
          
        List = treeService. getTreesByParentId (id); // The tree attributes displayed on the foreground, such as id, state, text, and checked.
          
           
        EList = new ArrayList
           
            
        (); If (list. size ()! = 0) {for (TreeDTO t: list) {EasyUITree e = new EasyUITree (); e. setId (t. getId (); e. setText (t. getText (); Map
            
             
        Attributes = new HashMap
             
              
        (); Attributes. put ("url", t. getUrl (); e. setAttributes (attributes); int count = treeService. countChildrens (t. getId (); if (count> 0) {// note the state attribute. When it is open, it indicates that the node is a folder and will be displayed as a folder. // when it is closed, it indicates the node. is a specific file node and is not displayed as a folder. E. setState ("closed");} eList. add (e) ;}} id = null; // convert the set containing information used to display the tree into json format and upload it to the foreground. WriteJson. pwObj (eList);} public TreeService getTreeService () {return treeService;} public void setTreeService (TreeService treeService) {this. treeService = treeService;} public String getId () {return id;} public void setId (String id) {this. id = id ;}}
             
            
           
          
         

        3. The underlying TreeDAOImpl serveice is omitted:
        package com.chy.ssh.business.dao;import java.util.ArrayList;import java.util.List;import org.springframework.dao.DataAccessException;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.chy.ssh.business.bean.TreeDTO;public class TreeDAOImpl extends HibernateDaoSupport implements TreeDAO {public int countChildrens(String id) {return Integer.parseInt(String.valueOf(this.getHibernateTemplate().find("select count(*) from TreeDTO t where t.pid = '"+id+"'").get(0)));}@SuppressWarnings("unchecked")public List
         
           getTreesByParentId(String id) {StringBuffer hql = new StringBuffer();if(id == null || "".equals(id)){hql.append("from TreeDTO t where t.pid is null ");}else{hql.append("from TreeDTO t where t.pid = '"+id+"' ");}List
          
            list = new ArrayList
           
            ();try {list = this.getHibernateTemplate().find(hql.toString());} catch (DataAccessException e) {e.printStackTrace();}return list;}}
           
          
         


        More: java_easyui system directory-00

        Contact Us

        The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

        If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

        A Free Trial That Lets You Build Big!

        Start building with 50+ products and up to 12 months usage for Elastic Compute Service

        • Sales Support

          1 on 1 presale consultation

        • After-Sales Support

          24/7 Technical Support 6 Free Tickets per Quarter Faster Response

        • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.