Java STRUTS2 Framework with Ext JS processing JSON data Use example _java

Source: Internet
Author: User

Recently tried to use ExtJS to show the tree menu. It took a really hard time. The menu items in the tree menu need to be loaded dynamically, while the current version of ExtJS only supports JSON-formatted data. After checking some information, I decided to use Struts2 's json-plugin. First, according to the example to do a, but the result is not successful, the interface only out of a JS generated root node, can not load data generated from the background. After the study, the data format was found to be problematic. The data format generated using Json-plugin is as follows:

{"CLS": "Folder", "id": "leaf": false, "children": [{"CLS": "File", "id": One, "leaf": true, "children": null, "text": " S600 "},{" CLS: "File", "id": "leaf": true, "children": null, "text": "SLK200"}, "text": "Benz"}

The data format required for ExtJS is as follows:

[{"CLS": "Folder", "id": "leaf": false, "children": [{"CLS": "File", "id": One, "leaf": true, "children": null, "text": " S600 "},{" CLS: "File", "id": "leaf": true, "children": null, "text": "SLK200"}, "text": "Benz"}]

The difference is very small, only the outermost two square brackets. But without these two square brackets, in JSON, the meaning is very different, the former represents an object, and the latter represents an array. The Dataloader required for the tree in ExtJS must be an array. And such data format is json-plugin automatically generated, cannot change. So I finally gave up json-plugin and instead used json-lib to solve the problem.
1. Download Json-lib, http://json-lib.sourceforge.net/
2. The 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/ Java
 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>

And then the 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 "class=" com.lab.MenuAction ">
  <result >/menu.jsp</result>
 </action>
 </package>
</struts>

3. Node model of the tree (omitted Getter,setter)

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);
 
 Menus.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 to "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 used the reorder.html and reorder.js in the ExtJS example, and changed the Reorder.js Treeloader in Dataurl:menus.action

 

Js:

*
 * Ext JS Library 2.0.1
 * Copyright (c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * *
 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. Resolve to list data
The code is as follows:
JSON data in the ExtJS

var combostore = new Ext.data.Store ({ 
 proxy:new Ext.data.HttpProxy ({ 
   URL: ' AdminGroup ',//here is Struts request to action 
   method: ' POST '//Request mode 
  }, 
 reader:new Ext.data.JsonReader ({//  
  total record number 
   Totalproperty: ' Results ',// Total records 
   root: ' Items ',//record collection 
   ID: ' Roleid ' 
  }, 
  [' Roleid ', ' rolename ']//Display two fields 
 }); 


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}



Here's the action code inside the struts2 that encapsulates the Exthelper tool class, which has transformed XML and JSON two formats

Public String FindAll () throws exception{ 
 
  httpservletrequest request = Servletactioncontext.getrequest (); 
 
  HttpServletResponse response = Servletactioncontext.getresponse (); 
 
  List List = Groupservice.getgroup (); Call the method inside the service to query all the data 
 
  String JSON = exthelper.getjsonfromlist (list);//Convert list to JSON-formatted data 
 
  Response.setcontenttype ("Text/json;charset=utf-8")//Set data to the foreground display character encoding, if no transfer has garbled 
 
  Response.getwriter (). Write ( JSON); 
 
  SYSTEM.OUT.PRINTLN (JSON); 
 
  return null; 
} 

There are a lot of ways to parse JSON, so it's convenient to do it in your own package, but if you're using STRUTS2 in your project, it's more convenient to use the Struts2 method directly.

Related Article

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.