Recently I tried using extjs to show a tree-like menu. It really took a lot of effort. Menu items of the tree-like menu need to be loaded dynamically, while the current version of extjs only supports JSON format data. After checking some information, I decided to use struts2's json-plugin. First, I made one according to the example, but the result was that it was unsuccessful. Only one root node generated in JS appeared on the interface, and the data generated from the background could not be loaded. After research, it was found that there was a problem with the data format. The data generated using json-plugin is as follows:
{"cls":"folder","id":10,"leaf":false,"children":[{"cls":"file","id":11,"leaf":true,"children":null,"text":"S600"},{"cls":"file","id":12,"leaf":true,"children":null,"text":"SLK200"}],"text":"Benz"} The data format required by extjs is as follows:
[{"cls":"folder","id":10,"leaf":false,"children":[{"cls":"file","id":11,"leaf":true,"children":null,"text":"S600"},{"cls":"file","id":12,"leaf":true,"children":null,"text":"SLK200"}],"text":"Benz"}] The difference is very small, so there are only two square brackets on the outermost difference. However, without these two square brackets, in json, the meaning is very different. The former represents an object, while the latter represents an array. The data required by the tree dataloader in extjs must be an array. And such a data format is automatically generated by json-plugin and cannot be changed. So, I ended up giving up json -plugin and instead used json-lib to solve this problem.
1. Download json-lib, http://json-lib.sourceforge.net/
2. List of jar files in the lib directory:
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-digester-1.6.jar
commons-lang-2.3.jar
commons-logging-1.1.jar
dom4j-1.6.1.jar
ezmorph-1.0.4.jar
freemarker-2.3.8.jar
javassist-3.8.1.jar
json-lib-2.2.1-jdk15.jar
log4j-1.2.13.jar
ognl-2.6.11.jar
struts2-core-2.0.11.jar
xml-apis-1.0.b2.jar
xwork-2.0.4.jar
First configure web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
Then there is 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> <constant name="struts.devMode" value="true"/> <constant name="struts.i18n.encoding" value="UTF-8"/> <package name="person" extends="struts-default"> <action name="menus" method="execute"> <result>/menu.jsp</result> </action> </package></struts>
3. Tree node model (getter, setter is omitted)
public class Menu { private int id; private String text; private boolean leaf; private String cls; private List<Menu> children;} 4. action
package com.lab;import java.util.ArrayList;import java.util.List;import net.sf.json.JSONArray;public class MenuAction { private String menuString; private List<Menu> menus; public String execute() { menus = new ArrayList<Menu>(); Menu benz = new Menu(); benz.setText("Benz"); benz.setCls("folder"); benz.setLeaf(false); benz.setId(10); menus.add(benz); List<Menu> benzList = new ArrayList<Menu>(); benz.setChildren(benzList); Menu menu; menu = new Menu(); menu.setText("S600"); menu.setCls("file"); menu.setLeaf(true); menu.setId(11); benzList.add(menu); menu = new Menu(); menu.setText("SLK200"); menu.setCls("file"); menu.setLeaf(true); menu.setId(12); benzList.add(menu); Menu bmw = new Menu(); bmw.setText("BMW"); bmw.setCls("folder"); bmw.setLeaf(false); bmw.setId(20); menu.add(bmw); List<Menu> bmwList = new ArrayList<Menu>(); bmw.setChildren(bmwList); menu = new Menu(); menu.setText("325i"); menu.setCls("file"); menu.setLeaf(true); menu.setId(21); bmwList.add(menu); menu = new Menu(); menu.setText("X5"); menu.setCls("file"); menu.setLeaf(true); menu.setId(22); bmwList.add(menu); JSONArray jsonObject = JSONArray.fromObject(menus); try { menuString = jsonObject.toString(); } catch (Exception e) { menuString = "ss"; } return "success"; } public String getMenuString() { return menuString; } public void setMenuString(String menuString) { this.menuString = menuString; }} 5. menu.jsp
<%@ taglib prefix="s" uri="/struts-tags" %><s:property value="menuString" escape="false"/>
6. html page and js
I am using reorder.html and reorder.js in the extjs example, and changed the dataurl of treeloader in reorder.js: menus.action
<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Reorder TreePanel</title><link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" /> <!-- GC --> <!-- LIBS --> <script type="text/javascript" src="extjs/adapter/ext/ext-base.js"></script> <!-- ENDLIBS --> <script type="text/javascript" src="extjs/ext-all.js"></script><script type="text/javascript" src="reorder.js"></script><!-- Common Styles for the examples --><link rel="stylesheet" type="text/css" href="extjs/resources/css/example.css" /></head><body><script type="text/javascript" src="../examples.js"></script><!-- EXAMPLES --><h1>Drag and Drop ordering in a TreePanel</h1><p>This example shows basic drag and drop node moving in a tree. In this implementation there are no restrictions and anything can be dropped anywhere except appending to nodes marked leaf (the files). <br></p><p>Drag along the edge of the tree to trigger auto scrolling while performing a drag and drop.</p><p>In order to demonstrate drag and drop insertion points, sorting was <b>not</b> enabled.</p><p>The data for this tree is asynchronously loaded with a JSON TreeLoader.</p><p>The js is not minified so it is readable. See <a href="reorder.js">reorder.js</a>.</p><div id="tree-div" style="overflow:auto; height:300px;width:250px;border:1px solid #c3daf9;"></div></body></html>
js:
/* * Ext JS Library 2.0.1 * Copyright(c) 2006-2008, Ext JS, LLC. * [email protected] * * http://extjs.com/license */Ext.onReady(function(){ // shorthand var Tree = Ext.tree; var tree = new Tree.TreePanel({ el:'tree-div', autoScroll:true, animate:true, enableDD:true, containerScroll: true, loader: new Tree.TreeLoader({ dataUrl:'http://localhost:8080/lab/menus.action' }) }); // set the root node var root = new Tree.AsyncTreeNode({ text: 'Ext JS', draggable:false, id:'source' }); tree.setRootNode(root); // render the tree tree.render(); root.expand();});
7. The code parsed into List data is as follows:
json data in EXTJS
var comboStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({ url:'adminGroup', //Here is the struts request to action method:'POST' //Request method}), reader: new Ext.data.JsonReader({ //Total records totalProperty: 'results', //Total records root: 'items', //Record collection id:'roleId' }, ['roleId','roleName'] //Two fields displayed) });
JSON data content
{"items":[{"password":"ahui","adminId":1,"role":{"roleName":"System Administrator","roleId":2,"sequence":"2","admin":null,"logoutMark":"No"},"adminName":"ahui","logout":"No"}, {"password":"xiao","adminId":2,"role":{"roleName":"System Administrator","roleId":2,"sequence":"2","admin":null,"logoutMark":"No"},"adminName":"xiao","logout":"Yes"},"results":13}
Below is the action code in struts2 encapsulates the ExtHelper tool class, which contains two formats: xml and json.
public String findAll() throws Exception{ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); List list = groupService.getGroup(); //Calling the method in service to query all data String json = ExtHelper.getJsonFromList(list);//Convert list to json format data response.setContentType("text/json;charset=UTF-8");//Set the character encoding displayed in the front desk. If the data is not transferred, there will be garbled response.getWriter().write(json); System.out.println(json); return null; }There are many ways to parse json, so how to be convenient is it. Json's own package can also be converted, but if you use Struts2 in the project, it is more convenient to use the method provided by Struts2 directly.