Creating a cascading application menu using Struts2 and YUI
January 19th, 2008 | by Admin |Yahoo User Interface (YUI) library is a set of Javascript based client side components for building highly interactive Web applications. All the YUI components work on the client side data. It also has built in Ajax support.
By integrating YUI to your Struts2 application, you can create cutting edge Web 2.0 rich client applications. In this post, I will show you how the YUI Menu component can be used along with Struts2 to create a cascading application menu.

Following are the components used in this sample project.
1. struts.xml - Struts2 action mappings.
2. web.xml - Configuration file for the sample web application
3. Menu.java - This encapsulates a Menu object. Can contain sub menus.
4. MenuDemoAction.java - Controller class for Menu demo. Contains code to populate sample Menu data. In real projects, you will populate this from database.
5. menudemo.jsp - This is a sample application screen with application menu at the top.
6. AppMenuTag.java - This is a custom tag library which renders a YUI based Menu bar.
7. menu.tld - The tag library configuration file inside WEB-INF folder.
In addition, this example uses the following css and JavaScript files provided as part of YUI. In real projects, these also must be part of your project.
8. http://yui.yahooapis.com/2.4.1/build/menu/assets/skins/sam/menu.css
9. http://yui.yahooapis.com/2.4.1/build/yahoo-dom-event/yahoo-dom-event.js
10. http://yui.yahooapis.com/2.4.1/build/container/container_core-min.js
11. http://yui.yahooapis.com/2.4.1/build/menu/menu-min.js
12. http://yui.yahooapis.com/2.4.1/build/json/json-beta-min.js
Now let us see how the code works.
When user accesses http://localhost:8080/struts2demo/MenuDemoAction.action, MenuDemoAction’s execute is invoked. This prepares the Menu data. A list of Menu objects is created. Each of this in turn can contain sub menus. After this control is passed to menudemo.jsp. In real applications, this will be fed from an XML file or from database tables.
menudemo.jsp contains AppMenuTag and it is invoked during JSP rendering. This converts the Menu object structure to a JSON structure using a YUI library. This JSON structure is given as input to the YUI menu control which renders the CSS based menu on the screen! Can it be any simpler? This whole project took me about 20 minutes to implement and test.
Now using similar techniques you can implement a wide range of controls available in YUI. These include tree, grid etc. which are frequently required in Web applications. YUI also contains utility functions such as a JSON library and methods for AJax interaction (YUI Connect).