최근에 나는 extjs를 사용하여 나무와 같은 메뉴를 보여주었습니다. 정말 많은 노력이 필요했습니다. 트리와 같은 메뉴의 메뉴 항목은 동적으로로드해야하며 현재 버전의 ExtJS는 JSON 형식 데이터 만 지원합니다. 정보를 확인한 후 Struts2의 JSON-Plugin을 사용하기로 결정했습니다. 먼저, 나는 예제에 따라 하나를 만들었지 만 결과는 그것이 실패했다는 것입니다. JS에서 생성 된 하나의 루트 노드 만 인터페이스에 나타 났으며 배경에서 생성 된 데이터를로드 할 수 없습니다. 연구 후, 데이터 형식에 문제가 있음이 밝혀졌습니다. JSON-Plugin을 사용하여 생성 된 데이터는 다음과 같습니다.
{ "CLS": "폴더", "ID": 10, "Leaf": False, "Children": [{ "cls": "file", "id": "Leaf": true, "children": null , "text": "s600"}, { "cls": "file", "id": "12,"leaf ": true,"children ": null,"text ":"slk200 "}],"text ":"Benz "} extjs가 요구하는 데이터 형식은 다음과 같습니다.
[{ "cls": "폴더", "id": 10, "잎": false, "children": [{ "cls": "file", "id": "leaf": true, "children": null , "text": "s600"}, { "cls": "file", "id": 12, "leaf": true, "children": null, "text": "slk200"}], "text": "Benz"}] 차이는 매우 작기 때문에 가장 바깥 쪽 차이에는 두 개의 정사각형 괄호 만 있습니다. 그러나 JSON에서는이 두 개의 정사각형 괄호가 없으면 의미가 매우 다릅니다. 전자는 객체를 나타내고 후자는 배열을 나타냅니다. ExtJS의 트리 데이터 로더가 요구하는 데이터는 배열이어야합니다. 이러한 데이터 형식은 JSON-Plugin에 의해 자동으로 생성되며 변경할 수 없습니다. 그래서 나는 JSON -Plugin을 포기하고 대신 JSON -LIB를 사용 하여이 문제를 해결했습니다.
1. JSON-Lib, http://json-lib.sourceforge.net/ 다운로드
2. LIB 디렉토리의 JAR 파일 목록 :
Commons-Beanutils-1.7.0.jar
커먼즈 컬렉션 -3.2.jar
Commons Digester-1.6.jar
Commons-Lang-2.3.jar
커먼즈 로깅 1.1.jar
dom4j-1.6.1.jar
ezmorph-1.0.4.jar
프리 마커 -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
먼저 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-instance-instance-- xsi : schemalocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <Welcome-File> <welcome-file> index.jsp </welcce-file> </welcome-list> <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> </web-pattern>
그런 다음 struts.xml이 있습니다
<? xml version = "1.0"encoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <constant name = "struts.i18n.encoding"value = "utf-8"/> <package name = "person"extends = "struts-default"> <action name = "menus"method = "execute"> <ectse "
3. 트리 노드 모델 (Getter, Setter가 생략 됨)
공개 수업 메뉴 {private int id; 개인 문자열 텍스트; 개인 부울 잎; 개인 문자열 CLS; 개인 목록 <메뉴> 어린이;} 4. 행동
패키지 com.lab; import java.util.arraylist; import java.util.list; import net.sf.json.jsonarray; public class menuaction {private String menustring; 개인 목록 <메뉴> 메뉴; public string execute () {memus = new arraylist <menu> (); 메뉴 벤츠 = 새 메뉴 (); Benz.settext ( "Benz"); Benz.setcls ( "폴더"); 벤츠 세트 리프 (false); Benz.setid (10); 메뉴 .add (벤츠); List <메뉴> BenzList = New ArrayList <메뉴> (); Benz.Setchildren (Benzlist); 메뉴 메뉴; 메뉴 = 새 메뉴 (); menu.settext ( "S600"); menu.setcls ( "파일"); menu.setLeaf (true); menu.setid (11); Benzlist.add (메뉴); 메뉴 = 새 메뉴 (); menu.settext ( "SLK200"); menu.setcls ( "파일"); menu.setLeaf (true); menu.setid (12); Benzlist.add (메뉴); 메뉴 bmw = 새 메뉴 (); bmw.settext ( "bmw"); bmw.setcls ( "폴더"); bmw.setleaf (false); BMW.SetID (20); menu.add (bmw); 목록 <메뉴> bmwlist = new ArrayList <메뉴> (); bmw.setchildren (bmwlist); 메뉴 = 새 메뉴 (); menu.settext ( "325i"); menu.setcls ( "파일"); menu.setLeaf (true); menu.setid (21); bmwlist.add (메뉴); 메뉴 = 새 메뉴 (); menu.settext ( "x5"); menu.setcls ( "파일"); menu.setLeaf (true); menu.setid (22); bmwlist.add (메뉴); jsonarray jsonobject = jsonarray.fromobject (메뉴); try {menustring = jsonobject.tostring (); } catch (예외 e) {menustring = "ss"; } 반환 "성공"; } public String getMenustring () {return menustring; } public void setMenustring (String menustring) {this.menustring = menustring; }} 5. Menu.jsp
< %@ taglib prefix = "s"uri = "/struts-tags" %> <s : 속성 값 = "menustring"탈출 = "false"/>
6. HTML 페이지 및 JS
extjs 예제에서 reourder.html 및 reorder.js를 사용하고 있으며 reorder.js : menus.action에서 treeloader의 dataurl을 변경했습니다.
<html> <head> <meta http-equiv = "content-type"content = "text/html; charset = iso-8859-1"> title> treepanel </title> <link rel = "Stylesheet"type = "text/css"href = "extjs/resources/css/ext-all.cs"/>>>>>>>>>> css "/>> <! -> <script type = "text/javaScript"src = "extjs/어댑터/ext/ext-base.js"> </script> <!-endlibs-> <script type = "text/javascript"src = "extjs/ext-all.js"> </script> <text/javascript " src = "reorder.js"> </script> <!-예제의 일반적인 스타일-> <link rel = "stylesheet"type = "text/css"href = "extjs/resources/css/exames.css"/> </head> <body> <cript type = "text/javaScript"src = ".. -> <H1> 트리 파넬에서 순서를 끌고 드롭 순서 </h1> <p>이 예는 트리에서 기본 드래그 앤 드롭 노드가 움직이는 것을 보여줍니다. 이 구현에서는 제한이 없으며 노드가 표시된 잎 (파일)에 추가되는 것 외에는 아무것도 삭제할 수 있습니다. <br> </p> <p> 드래그 앤 드롭을 수행하는 동안 자동 스크롤을 트리거하기 위해 트리의 가장자리를 따라 드래그하여 자동 스크롤을 트리거합니다. </p> <p> 드래그 앤 드롭 삽입 지점을 보여주기 위해 정렬은 <b> </b>가 활성화되지 않았습니다. </p> <p>이 트리의 데이터는 JSON 트리 로더와 비교적으로로드되었습니다. <a href = "reorder.js"> reorder.js </a> </a>
JS :
/ * * EXT JS 라이브러리 2.0.1 * 저작권 (C) 2006-2008, Ext JS, LLC. * [email protected] * * http://extjs.com/license */ext.onready (function () {// ghorthand var tree = var tree = new tree.treepanel ({el : 'tree-div', autoScroll : true, animate : enabledd : true : true, 로딩 : 새로운 tree. DATERL : // LocalHost : 8080/Lab/MERUS.ACTION '});
7. 목록 데이터로 구분 된 코드는 다음과 같습니다.
extjs의 JSON 데이터
var combostore = new ext.data.store ({proxy : new ext.data.httpproxy ({url : 'admingroup', // 여기에 struts request to action method : 'post'// request method}), 독자 : 새로운 ext.data.jsonreader ({// Total Records ','recets ','records ','records ','records ' id : 'realID'}, [ 'rolId', 'rolename'] // 두 필드가 표시됨)});
JSON 데이터 컨텐츠
{ "항목": [{ "password": "ahui", "adminid": 1, "역할": { "rolename": "system indecrator", "system invinmentator", "system 관리자", "2,"시퀀스 ":"2 ","admin ":"no "},"adminname ":"ahui ","logout ":"}, "},"}, { "password": "xiao", "adminid": 2, "robol": { "rolename": "System Administrator", "rolearId": "Sequence": "2", "admin": "logoutmark": "no"}, "adminname": "Xiao", "yors": "yes"}, "결과"}.
아래는 struts2의 액션 코드입니다. XML과 JSON의 두 가지 형식이 포함 된 Exthelper 도구 클래스를 캡슐화합니다.
public string findall ()은 예외를 던지고 {httpservletrequest 요청 = servletactionContext.getRequest (); httpservletResponse 응답 = servletactionContext.getResponse (); List List = GroupService.getGroup (); // 모든 데이터 문자열 json = exthelper.getJsonfromList (list); // 목록을 JSON 형식 데이터 응답으로 변환하기 위해 서비스중인 메소드를 호출합니다. Data Response.setContentType ( "text/json; charset = utf-8"); // 프론트 데스크에 표시되는 문자를 설정합니다. 데이터가 전송되지 않으면 rankled response.getWriter (). 쓰기 (json); System.out.println (JSON); 널 리턴; }JSON을 구문 분석하는 방법에는 여러 가지가 있으므로 편리한 방법이 있습니다. JSON의 자체 패키지도 변환 할 수 있지만 프로젝트에서 struts2를 사용하는 경우 Struts2에서 제공하는 방법을 직접 사용하는 것이 더 편리합니다.