Using SSH + easyui to display data in the treegrid tree

Source: Internet
Author: User

This article introduces the combination of struts2, spring, hibernate, and easyui treegrid to present data in the database in the form of a tree. During development, many data needs to be presented in the form of trees, such as navigation bars and resource management in the permission management module. Generally, databases exist in the form of trees. The example program uses resource management as an example to use treegrid to display the data of the Resource Management submodule. The final effect is as follows:


It is easy to use easyui to display the tree. You only need to set the class of the <Table> label to easyui-treegrid.

<Body class = "easyui-layout" data-Options = "Fit: True, border: false"> <div> <span style = "white-space: pre "> </span> <Table id =" resourcelist "class =" easyui-treegrid "data-Options =" url: 'privilegemgmt/resourceaction_getall.action ', idfield: 'id ', treefield: 'resourcename', toolbar: '# tb', border: false "> <thead> <tr> <TH data-Options =" field: 'id', width: 40 "> Number </Th> <TH data-Options =" field: 'resourcename', width: 150 "> Resource Name </Th> <TH data-Options =" field: 'resourceurl', width: 200 "> resource path </Th> <TH data-Options =" field: 'resourceorder', width: 50 "> sort </Th> <TH data-Options =" field: 'icon ', width: 80 "> icon </Th> <TH data-Options =" field: 'resourcetype', width: 80 "> Resource Type </Th> <TH data-Options =" field: 'parentid', width: 80 "> parent resource id </Th> <TH data-Options =" field: 'enable', width: 50 "> Status </Th> <TH data-Options =" field: 'action', width: 120 "> operation </Th> </tr> </thead> <span style =" white-space: pre "> </span> </table> <span style =" white-space: pre "> </span> <Div id =" TB "> <span style =" white-space: pre "> </span> <a href =" javascript: void (0) "class =" easyui-linkbutton "iconcls =" icon-Add "plain =" true "onclick =" onadd () "> added </a> <span style =" white-space: pre "> </span> <a href =" javascript: void (0) "Class =" easyui-linkbutton "iconcls =" icon-edit "plain =" true "onclick =" onupdate () "> edit </a> <span style =" white-space: pre "> </span> <a href =" javascript: void (0) "Class =" easyui-linkbutton "iconcls =" icon-Remove "plain =" true "onclick =" ondelete () "> Delete </a> <span style =" white-space: pre "> </span> </div> </body>

The preceding figure shows the HTML code in a tree. The attribute values defined by data-options are as follows:

URL: defines the path for remote data retrieval. The data is returned in JSON format.

Idfield: ID of the Tree node. This value is unique.

Treefield: defines the node field. For example, the node field defined above is the resource name. When the node contains a subnode, a scalable icon is displayed before the Resource Name.

Toolbar: toolbar. The input parameter is the ID value of the HTML Tag.

Border: whether to display borders

Field: field name, that is, the data to be displayed in the column. easyui parses JSON strings and outputs them to the form cyclically, determine which data is output to which column based on the field name matching the field in the JSON string

Formatter: Cell formatter function, which is used to format the data display of the column to achieve the desired display effect. The function contains three parameters: Value (field value), rowdata (row record data), and rowindex (row index ).

Next, access action to obtain data from the server. The above calls the getall method of resourceaction to obtain the Resource Tree.

Resourceaction. Java

public class ResourceAction extends BaseAction {private Resource resource;private ResourceServiceI resourceService;public void getAll() {String json = resourceService.getResourceTreeToJson();this.write(json);}//getter or setterpublic Resource getResource() {return resource;}public void setResource(Resource resource) {this.resource = resource;}public ResourceServiceI getResourceService() {return resourceService;}public void setResourceService(ResourceServiceI resourceService) {this.resourceService = resourceService;}}
Baseaction. Java
public abstract class BaseAction extends ActionSupport {public void write(String json) {try {ServletActionContext.getResponse().setCharacterEncoding("UTF-8");ServletActionContext.getResponse().setContentType("text/json");ServletActionContext.getResponse().getWriter().write(json);ServletActionContext.getResponse().getWriter().flush();ServletActionContext.getResponse().getWriter().close();} catch (Exception ex) {Debuger.log("BaseAction write json throw Exception!");ex.printStackTrace();}}public void write(boolean bool) {try {String json = "{\"success\":\"" + bool + "\"}";ServletActionContext.getResponse().getWriter().write(json);ServletActionContext.getResponse().getWriter().flush();ServletActionContext.getResponse().getWriter().close();} catch (Exception ex) {Debuger.log("BaseAction write bool throw Exception!");ex.printStackTrace();}}}

Struts. xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    "http://struts.apache.org/dtds/struts-2.0.dtd"><struts><package name="priviligemgmt" extends="struts-default" namespace="/privilegemgmt"><action name="resourceAction_*" class="com.wzh_1208.sshe.action.ResourceAction" method="{1}">   <result name="input">/jsp/privilegemgmt/resourceinfo.jsp</result></action></package></struts>
When using the class provided by the framework, I generally encapsulate it into an abstract class of my own, and then I need to use it to directly inherit my own base class, so as to facilitate expansion and code reuse. Because most actions in the project need to write JSON strings to the client, two write methods are encapsulated in baseaction, and other actions inherit baseacion. The getall method is actually a shell for JSP page calling. All the logic is lost to the getresourcetreetojson method in the business logic layer. This method encapsulates the resources in the database into a tree, and return it as a JSON string.

Resourceserviceimpl. Java

Import Java. util. list; import net. SF. JSON. jsonarray; import net. SF. JSON. jsonobject; import COM. wzh_1208.waimai.bean.resource; import COM. wzh_1208.waimai.dao.resourcedaoi; import COM. wzh_1208.waimai.services.resourceservicei; public class resourceserviceimpl implements resourceservicei {private resourcedaoi resourcedao; @ overridepublic list <resource> getallresource () {return resourcedao. findall () ;}@ overrid Epublic string getresourcetreetojson () {return this. createtreejson (getallresource ();}/*** create a tree, return the * @ Param list raw data list * @ return tree */private string createtreejson (list <resource> List) {jsonarray rootarray = new jsonarray (); for (INT I = 0; I <list. size (); I ++) {resource = List. get (I); If (resource. getparentid () = NULL) {jsonobject rootobj = createbranch (list, resource); rootarray. Add (rootobj) ;}} return rootarray. tostring ();} /*** recursively create the JSON object of the branch node * @ Param List Original data of the tree creation * @ Param currentnode current node * @ return JSON object of the current node and Its subnode */ private jsonobject createbranch (list <resource> list, resource currentnode) {/** resolve the JavaBean object to a JSON object */jsonobject currentobj = jsonobject. fromobject (currentnode); jsonarray childarray = new jsonarray ();/** traverses the original data list cyclically to determine whether the parent id value of an object in the list is equal to the ID value of the current node, * if they are equal, enter Recursively create a subnode of a new node until there is no subnode, return to the node, and put the * node into the subnode list of the current node */For (INT I = 0; I <list. size (); I ++) {resource newnode = List. get (I); If (newnode. getparentid ()! = NULL & newnode. getparentid (). compareto (currentnode. GETID () = 0) {jsonobject childobj = createbranch (list, newnode); childarray. add (childobj) ;}}/** determines whether the current child node array is empty. If not, add the child node array to the children field */If (! Childarray. isempty () {currentobj. put ("children", childarray);} return currentobj;} // getter or setterpublic resourcedaoi getresourcedao () {return resourcedao;} public void setresourcedao (resourcedaoi resourcedao) {This. resourcedao = resourcedao ;}}

When easyui's treegrid is used, the most important thing is that the server uses the JSON data format returned by easyui. When processing the JSON string returned from the server, easyui determines whether the current node contains a subnode based on whether the children field and data are included in the node. Therefore, when returning JSON data, you must add the children field to the node that contains the subnode and assign the subnode list to this value. Resourceserviceimpl is the implementation class of resourceservicei. The getallresource () and getresourcetojson () methods are implemented. The getallresource () method calls the Database Access Object resourcedaoimpl to obtain the list of all resources in the database and return them, the getresourcetojson method Retrieves all resources and organizes them into a tree, which is returned as a JSON string.

Resourcedaoimpl. Java

Import Java. SQL. timestamp; import Java. util. list; import Org. slf4j. logger; import Org. slf4j. loggerfactory; import COM. wzh_1208.waimai.basedao; import COM. wzh_1208.waimai.bean.resource; import COM. wzh_1208.waimai.dao.resourcedaoi; public class resourcedaoimpl extends basedao implements resourcedaoi {Private Static final logger log = loggerfactory. getlogger (resourcedaoimpl. class); protected void initdao () {// do nothing} public list <resource> findall () {log. debug ("finding all resource instances"); try {// query resource records, sorted in ascending order by the resource parent ID and serial number string querystring = "from resource order by parentid, resourceorder ASC "; return gethibernatetemplate (). find (querystring);} catch (runtimeexception re) {log. error ("Find all failed", RE); throw re ;}}}
Basedao. Java

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;public abstract class BaseDAO extends HibernateDaoSupport {}
Resourcedaoimpl inherits the basedao class and resourcedaoi, implements the findall method, and returns all resource records sorted by resource parent ID and serial number in ascending order for the business logic layer.

The above completes the implementation of the entire data presentation process, but the work is not completed yet, and a lot of configuration files need to be configured. I will not post it here.

Resource. Java

Import Java. SQL. timestamp;/*** resource entity. @ author wzh */public class resource implements Java. io. serializable {// primary key idprivate integer ID; // Resource Name private string resourcename; // resource access path private string resourceurl; // Resource Description private string description; // resource icon private string icon; // parent node idprivate integer parentid; // resource type, menu or button private string resourcetype; // whether private integer enable is available; // resource sorting No. Private integer resourceorder; // creation time private timestamp createtime; <span style = "white-space: pre ">/** default constructor */<span style =" white-space: pre "> </span> public resource () {<span style =" white-space: pre "> </SPAN >}</span> // The getter or setter method is omitted ........}
Resource. HBM. xml

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Run the program, and the data can be displayed in the form of a tree, as shown below:

However, the data in the database is displayed on the interface, the Set icon, status available or disabled, and Operation column are not displayed on the node like the figure at the beginning of the article. In this case, The formatter attribute of easyui is used to define the display function of the formatting column to customize the display of data. The modified HTML code is as follows:

<SCRIPT>/*** format the resource display name. When easyui displays the node field, if the record contains the iconcls value, easyui uses the corresponding icon according to the value, * If not, use the default icon instead. Here, the passed JSON string does not contain the iconcls field, but contains the icon field. Here, you only need to assign the icon field value to iconcls to display the icon. **/Function formatname (value, row, index) {// The icon displayed before the name depends on the iconcls attribute, and the iconcls attribute is a CSS class, when easyui obtains this attribute value, the corresponding icon is displayed. // The passed JSON string does not contain the iconcls attribute, and only the icon attribute is displayed, therefore, to display the easyui icon, you only need to assign the icon value to iconclsrow. iconcls = row. icon; return value;}/*** format the display of the parent resource. If the value is 0, the parent resource is not displayed. **/function formatparentid (value, row, index) {If (value = 0) {return NULL;} return value;}/*** format status. If the value is 1, the format is normal, disabled for 0 */function formatstate (value, row, index) {Switch (value) {Case 1: Return 'normal'; Case 0: Return 'deactivated ';}} /*** formatting operation. The edit and delete operations are displayed in the Operation column of each row */function formataction (value, row, index) {var STR = ''; If (true) {STR + = '<a href = "javascript: onupdate ()"> edit </a>';} STR + = '|'; If (true) {STR + = '<a href = "javascript: ondelete ()"> Delete </a>';} return STR ;} </SCRIPT> From the code above, we can see that the formatter attribute and the corresponding called Formatting Function are added to the data-options attribute of the <TH> label of the column to be formatted, the specific functions and functions are now described in the Code. Note that the iconcls field value is a class of CSS. You can use the icons provided by easyui or custom icons. If you use a custom icon, be sure to pay special attention to the icon path, otherwise it cannot be displayed normally.

In this way, the treegrid attribute is used to display resource data.

Source code download: http://download.csdn.net/detail/a78460750/7811961

Using SSH + easyui to display data in the treegrid tree

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.