KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jdon > strutsutil > treeview > TreeControlTag


1 /**
2  * Copyright 2003-2006 the original author or authors.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6
7        http://www.apache.org/licenses/LICENSE-2.0
8
9   * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */

15
16 package com.jdon.strutsutil.treeview;
17
18 import java.io.IOException JavaDoc;
19 import java.net.URLEncoder JavaDoc;
20 import javax.servlet.http.*;
21 import javax.servlet.jsp.JspException JavaDoc;
22 import javax.servlet.jsp.JspWriter JavaDoc;
23 import javax.servlet.jsp.tagext.TagSupport JavaDoc;
24
25 /**
26  * 树形结构显示
27  * 类似javascript实现功能,主è¦?是输出Html语å?¥ï¼Œç”¨äºŽæ˜¾ç¤ºæ ‘形结构。
28  *
29  *
30  * ViewNode :表示三层关系节点
31  * TreeControl:整个树形结构节点的ä¿?存器(HashMap)
32  * 本类根æ?®ä»¥ä¸Šä¸¤ä¸ªåŸºç±»ï¼Œä»¥levelå’Œwidth两个å?˜é‡?æ?¥ç»˜åˆ¶table表格。
33  *
34  *
35  * <TreeView:tree
36                  treeAction="updateTreeAction.do"
37                 nodeAction="categoryAction.do?action=edit&catId=${key}"
38                 target="content"
39   />
40  *
41  *
42  */

43 public class TreeControlTag extends TagSupport JavaDoc {
44
45   private final static String JavaDoc module = TreeControlTag.class.getName();
46
47   /**
48    * The default directory name for icon images.
49    */

50   private static final String JavaDoc DEFAULT_IMAGES = "images";
51
52   public static final String JavaDoc TREE_NAME = "tree-control";
53   public static final String JavaDoc TREE_NAME_INIT = "tree-control-init";
54
55
56   private static final String JavaDoc CSS_STYLE = "tree-control";
57   private static final String JavaDoc CSS_STYLE_SELECTED = "tree-control-selected";
58   private static final String JavaDoc CSS_STYLE_UN_SELECTED = "tree-control-unselected";
59
60   /**
61    * The names of tree state images that we need.
62    */

63   private static final String JavaDoc IMAGE_HANDLE_DOWN_LAST = "handledownlast.gif";
64   private static final String JavaDoc IMAGE_HANDLE_DOWN_MIDDLE = "handledownmiddle.gif";
65   private static final String JavaDoc IMAGE_HANDLE_RIGHT_LAST = "handlerightlast.gif";
66   private static final String JavaDoc IMAGE_HANDLE_RIGHT_MIDDLE =
67       "handlerightmiddle.gif";
68   private static final String JavaDoc IMAGE_LINE_LAST = "linelastnode.gif";
69   private static final String JavaDoc IMAGE_LINE_MIDDLE = "linemiddlenode.gif";
70   private static final String JavaDoc IMAGE_LINE_VERTICAL = "linevertical.gif";
71
72
73   // ------------------------------------------------------------- Properties
74

75   protected String JavaDoc treeAction = null;
76   public String JavaDoc getTreeAction() {
77     return (this.treeAction);
78   }
79
80   public void setTreeAction(String JavaDoc treeAction) {
81     this.treeAction = treeAction;
82   }
83
84   protected String JavaDoc nodeAction = null;
85   public String JavaDoc getNodeAction() {
86     return (this.nodeAction);
87   }
88
89   public void setNodeAction(String JavaDoc nodeAction) {
90     this.nodeAction = nodeAction;
91   }
92
93   protected String JavaDoc target = null;
94
95   public String JavaDoc getTarget() {
96     return (this.target);
97   }
98
99   public void setTarget(String JavaDoc target) {
100     this.target = target;
101   }
102
103   protected String JavaDoc images = DEFAULT_IMAGES;
104   public String JavaDoc getImages() {
105     return (this.images);
106   }
107
108   public void setImages(String JavaDoc images) {
109     this.images = images;
110   }
111
112   public int doEndTag() throws JspException JavaDoc {
113
114     TreeControl treeControl = (TreeControl) pageContext.findAttribute(TREE_NAME);
115     JspWriter JavaDoc out = pageContext.getOut();
116
117     try {
118       if (treeControl == null) {
119         out.print("Please login again, or refresh again");
120         return (EVAL_PAGE);
121       }
122
123       out.print
124           ("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"");
125       out.print(" class=\"");
126       out.print(CSS_STYLE);
127       out.print("\"");
128       out.println(">");
129       int level = 0;
130       ViewNode rootNode = treeControl.getRoot();
131       render(out, rootNode, level, treeControl.getTreeWidth(), true);
132       out.println("</table>");
133     } catch (IOException JavaDoc e) {
134       throw new JspException JavaDoc(e);
135     } catch (Exception JavaDoc e) {
136       throw new JspException JavaDoc("Please refresh this page!");
137     }
138
139     return (EVAL_PAGE);
140
141   }
142
143   //level是当å‰?层
144
protected void render(JspWriter JavaDoc out, ViewNode node,
145                         int level, int width, boolean last) throws IOException JavaDoc {
146
147     HttpServletResponse response =
148         (HttpServletResponse) pageContext.getResponse();
149
150     HttpServletRequest request =
151         (HttpServletRequest) pageContext.getRequest();
152     String JavaDoc url_Path = request.getContextPath();
153
154 // Debug.logVerbose("[JdonFramework] node key=" + node.getKey() + " level=" + level +
155
// " width=" + width + " last=" + last, module);
156

157     //如果是根节点或无标签,ä¸?显示该节点
158
if (node.isRoot()) {
159       // Render the children of this node
160
ViewNode children[] = node.findChildren();
161 // Debug.logVerbose("[JdonFramework] children count =" + children.length);
162
int lastIndex = children.length - 1;
163       int newLevel = level + 1;
164       for (int i = 0; i < children.length; i++) {
165         render(out, children[i], newLevel, width, i == lastIndex);
166       }
167       return;
168     }
169
170     // Render the beginning of this node
171
out.println(" <tr valign=\"middle\">");
172
173     for (int i = 0; i < level; i++) {
174       int levels = level - i;
175       ViewNode parent = node;
176       for (int j = 1; j <= levels; j++)
177         parent = parent.getParent();
178       if (parent.isLast())
179         out.print(" <td></td>");
180       else { //显示竖线
181
out.print(" <td><img SRC=\"");
182         out.print(images);
183         out.print("/");
184         out.print(IMAGE_LINE_VERTICAL);
185         out.print("\" alt=\"\" border=\"0\"></td>");
186       }
187       out.println();
188     }
189
190     displayNodePic(out, node, url_Path);
191     displayNode(out, node, url_Path, level, width);
192
193     // Render the end of this node
194
out.println(" </tr>");
195
196     // Render the children of this node
197
if (node.isExpanded()) {
198       ViewNode children[] = node.findChildren();
199       int lastIndex = children.length - 1;
200       int newLevel = level + 1;
201       for (int i = 0; i < children.length; i++) {
202         render(out, children[i], newLevel, width, i == lastIndex);
203       }
204     }
205
206   }
207
208   /**
209    *
210    * 显示节点å‰?图形符å?·ã€€ã€€å¼€å§‹
211    *
212    * 如果该节点有å­?节点,符å?·æ˜¾ç¤ºIMAGE_HANDLE图形
213    * 注:点按IMAGE_HANDLE,å?¯ä»¥å±•å¼€æ‰€æœ‰çš„å­?节点
214    * 如果无å­?节点,显示IMAGE_LINE
215    */

216   private void displayNodePic(JspWriter JavaDoc out, ViewNode node, String JavaDoc url_Path) throws
217       IOException JavaDoc {
218     HttpServletResponse response =
219         (HttpServletResponse) pageContext.getResponse();
220
221     StringBuffer JavaDoc url = new StringBuffer JavaDoc(url_Path);
222     url.append(treeAction);
223     if (treeAction.indexOf("?") < 0)
224       url.append("?");
225     else
226       url.append("&");
227     url.append("key=").append(node.getKey());
228
229     out.print(" <td>");
230     if ( (nodeAction != null) && !node.isLeaf()) {
231       out.print("<a HREF=\"");
232       out.print(response.encodeURL(url.toString()));
233       out.print("\">");
234     }
235     out.print("<img SRC=\"");
236     out.print(images);
237     out.print("/");
238     if (node.isLeaf()) {
239       if (node.isLast())
240         out.print(IMAGE_LINE_LAST);
241       else
242         out.print(IMAGE_LINE_MIDDLE);
243       out.print("\" alt=\"");
244     } else if (node.isExpanded()) {
245       if (node.isLast())
246         out.print(IMAGE_HANDLE_DOWN_LAST);
247       else
248         out.print(IMAGE_HANDLE_DOWN_MIDDLE);
249       out.print("\" alt=\"close node");
250     } else {
251       if (node.isLast())
252         out.print(IMAGE_HANDLE_RIGHT_LAST);
253       else
254         out.print(IMAGE_HANDLE_RIGHT_MIDDLE);
255       out.print("\" alt=\"expand node");
256     }
257     out.print("\" border=\"0\">");
258     if ( (nodeAction != null) && !node.isLeaf())
259       out.print("</a>");
260     out.println("</td>");
261   }
262
263   /**
264    * 显示节点本身信æ?¯ï¼Œå¦‚节点å??称等
265    *
266    * @throws IOException
267    */

268   private void displayNode(JspWriter JavaDoc out, ViewNode node, String JavaDoc url_Path,
269                            int level, int width) throws IOException JavaDoc {
270
271     HttpServletResponse response =
272         (HttpServletResponse) pageContext.getResponse();
273
274     //----------------------------------------显示节点本身信æ?¯ï¼Œå¦‚节点å??称等开始
275
String JavaDoc encodedNodeKey = URLEncoder.encode(node.getKey(), "UTF-8");
276     String JavaDoc action = replace(nodeAction, "${key}", encodedNodeKey);
277     StringBuffer JavaDoc url = new StringBuffer JavaDoc(url_Path);
278     url.append(action);
279     if (nodeAction.indexOf("?") < 0)
280       url.append("?");
281     else
282       url.append("&");
283     url.append("key=").append(node.getKey());
284     String JavaDoc treeNodeAction = url.toString();
285
286     url = new StringBuffer JavaDoc(url_Path);
287     url.append(treeAction);
288     if (treeAction.indexOf("?") < 0)
289       url.append("?");
290     else
291       url.append("&");
292     url.append("select=").append(node.getKey());
293     String JavaDoc updateNodeAction = url.toString();
294
295     // Render the label for this node (if any)
296
out.print(" <td colspan=\"");
297     out.print(width - level + 1);
298     out.print("\">");
299
300     //这里çœ?略了icon
301

302     if (node.getLabel() != null) {
303       String JavaDoc labelStyle = null;
304       if (node.isSelected())
305         labelStyle = CSS_STYLE_SELECTED;
306       else if (!node.isSelected())
307         labelStyle = CSS_STYLE_UN_SELECTED;
308       if (treeNodeAction != null) {
309         // Note the leading space so that the text has some space
310
// between it and any preceding images
311
out.print(" <a HREF=\"");
312         out.print(treeNodeAction);
313         out.print("\"");
314         if (target != null) {
315           out.print(" target=\"");
316           out.print(target);
317           out.print("\"");
318         }
319         if (labelStyle != null) {
320           out.print(" class=\"");
321           out.print(labelStyle);
322           out.print("\"");
323         }
324         // to refresh the tree in the same 'self' frame
325
out.print(" onclick=\"");
326         out.print("self.location.href='" + updateNodeAction + "'");
327         out.print("\"");
328         out.print(">");
329       } else if (labelStyle != null) {
330         out.print("<span class=\"");
331         out.print(labelStyle);
332         out.print("\">");
333       }
334       out.print(node.getLabel());
335       if (treeNodeAction != null)
336         out.print("</a>");
337       else if (labelStyle != null)
338         out.print("</span>");
339     }
340
341     out.println("</td>");
342
343     //----------------------------------------显示节点本身信æ?¯ï¼Œå¦‚节点å??称等结æ?Ÿ
344

345   }
346
347   /**
348    * Replace any occurrence of the specified placeholder in the specified
349    * template string with the specified replacement value.
350    *
351    * @param template Pattern string possibly containing the placeholder
352    * @param placeholder Placeholder expression to be replaced
353    * @param value Replacement value for the placeholder
354    */

355   protected String JavaDoc replace(String JavaDoc template, String JavaDoc placeholder,
356                            String JavaDoc value) {
357
358     if (template == null)
359       return (null);
360     if ( (placeholder == null) || (value == null))
361       return (template);
362     while (true) {
363       int index = template.indexOf(placeholder);
364       if (index < 0)
365         break;
366       StringBuffer JavaDoc temp = new StringBuffer JavaDoc(template.substring(0, index));
367       temp.append(value);
368       temp.append(template.substring(index + placeholder.length()));
369       template = temp.toString();
370     }
371     return (template);
372
373   }
374
375 }
376
Popular Tags