實戰Struts-Menu

okone96發表於2007-02-06

實戰Struts-Menu
一、簡介
Struts-Menu是一組從基於XML的配置檔案中生成多種樣式的選單的JSP Tags,並且可以結合API開發透過資料庫生成的動態選單。Struts-Menu支援國際化和多種許可權控制。

二、執行環境
Windows 2000 Professional
JDK 1.4.2_03
Eclipse 3.1
Tomcat 5.0.28
Tomcat Plugin 3.1Beta
Struts 1.2.7
Commons-Lang 2.1
Commons-Collections 3.1
Struts-Menu 2.3
MySQL 4.1.10a-nt

三、下載與安裝
1:從下載J2SDK,當前1.4.x系列的最新版本為1.4.2_08
2:從下載Eclipse,當前最新版本為3.1正式版
3:從下載Tomcat,當前5.x系列的最新版本為5.0.28
4:從下載Eclipse的Tomcat外掛,對應Eclipse3.1x的最新版本為3.1Beta
5:從下載Struts,當前最新版本為1.2.7
6:從下載Commons-Lang,當前最新版本為2.1,下載Commons-Collections,當前最新版本為3.1
7:從下載Struts Menu,當前最新版本為2.3
8:從下載MySQL資料庫,4.x系列的最新版本是4.1.12a
9:MySQL、JDK、Eclipse、Tomcat和TomcatPlugin的安裝及配置請參考相關資料

四、執行示例程式
1:安裝好Tomcat後,解壓縮struts-menu-2.3.zip,將struts-menu.war釋放到Tomcat安裝目錄下的webapps下,執行Tomcat
2:在位址列輸入

五、安裝與配置
1:在Eclipse中新建Tomcat專案,Context為/mymenu,Subdirectory為/web
2:在專案目錄下面新建lib目錄和web目錄及WEB-INF,在web/WEB-INF目錄下新建web.xml,內容如下:

br />PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"">


My Example Application -- Vinton Lee

<!-- ============= The Struts ActionServlet Configuration ============= --&gt

action
org.apache.struts.action.ActionServlet

config
/WEB-INF/struts-config.xml

1

<!-- ================================================================== --&gt

<!-- ============= The Struts Action Servlet Mapping ================== --&gt

action
*.do

<!-- ================================================================== --&gt

<!-- The Welcome File List --&gt

index.jsp

<!-- =============== The Struts Taglib Definition ===================== --&gt

struts-bean
/WEB-INF/struts-bean.tld


struts-html
/WEB-INF/struts-html.tld


struts-logic
/WEB-INF/struts-logic.tld


struts-nested
/WEB-INF/struts-nested.tld


struts-tiles
/WEB-INF/struts-tiles.tld

<!-- ================================================================== --&gt

<!-- ============= The Struts-Menu Taglib Definition ================== --&gt

struts-menu
/WEB-INF/struts-menu.tld

<!-- ================================================================== --&gt

3:解壓縮struts-1.2.7.zip,將壓縮包中的lib目錄下所有的8個jar釋放到lib目錄中,將5個tld檔案釋放到webWEB-INF目錄中,在webWEB-INF目錄中新建struts-config.xml,內容如下:

br />"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"">

<!-- ========== Data Source Configuration =============================== --&gt

<!-- ========== Form Bean Definitions =================================== --&gt

<!-- ========== Global Exception Definitions ============================ --&gt

<!-- ========== Global Forward Definitions ============================== --&gt

<!-- ========== Action Mapping Definitions ============================== --&gt

<!-- ========== Controller Configuration ================================ --&gt

<!-- ========== Message Resources Definitions =========================== --&gt

<!-- ========== Plug Ins Configuration ================================== --&gt


4:解壓縮struts-menu-2.3.zip,將壓縮包中的jstl-1.0.6.jar、standard-1.0.6.jar、struts-menu-2.3.jar釋放到lib目錄中,將壓縮包中的struts-menu.tld、struts-menu-el.tld釋放到webWEB-INF目錄中,解壓縮commons-lang-2.1.zip,將commons-lang-2.1.jar解壓縮到lib目錄中,注意,在Struts-Menu的文件中沒有看到需要這個包,但是沒有這個包卻無法成功載入。在webWEB-INF目錄中新建menu-config.xml,內容如下:


type="net.sf.navigator.displayer.DropDownMenuDisplayer"/>
type="net.sf.navigator.displayer.SimpleMenuDisplayer"/>
type="net.sf.navigator.displayer.CoolMenuDisplayer"/>
type="net.sf.navigator.displayer.CoolMenuDisplayer4"/>
type="net.sf.navigator.example.PermissionsFormMenuDisplayer"/>
type="net.sf.navigator.displayer.ListMenuDisplayer"/>
type="net.sf.navigator.displayer.TabbedMenuDisplayer"/>
type="net.sf.navigator.displayer.VelocityMenuDisplayer"/>





bundle="org.apache.struts.action.MESSAGE">


執行Tomcat,在IE位址列輸入檢視

2:實現中文化
> 在srcapplication_zh_CN.properties中增加下面的內容,Unicode可以透過JDK自帶的native2ascii工具得到:
#入口網站
menu.DoorSite=u95e8u6237u7f51u7ad9
#雅虎
menu.Yahoo=u96c5u864e
#雅虎首頁
menu.YahooIndex=u96c5u864eu9996u9875
#雅虎郵件
menu.YahooMail=u96c5u864eu90aeu4ef6
#搜狐
menu.Sohu=u641cu72d0
#新浪
menu.Sina=u65b0u6d6a
> 在srcapplication.properties中增加下面的內容:
#入口網站
menu.DoorSite=DoorSite
#雅虎
menu.Yahoo=Yahoo
#雅虎首頁
menu.YahooIndex=Yahoo Index
#雅虎郵件
menu.YahooMail=Yahoo Mail
#搜狐
menu.Sohu=Sohu
#新浪
menu.Sina=Sina
> 修改menu-config.xml檔案部分:



}

/**
* 建立選單資料結構
*
* @param request
*/
private void buildMenuRepository(HttpServletRequest request) {
MenuRepository repository = new MenuRepository();
// Get the repository from the application scope - and copy the
// DisplayerMappings from it.
MenuRepository defaultRepository = (MenuRepository) request
.getSession().getServletContext().getAttribute(
MenuRepository.MENU_REPOSITORY_KEY);
repository.setDisplayers(defaultRepository.getDisplayers());

Map[] menus = getMenuComponents();
for (int i=0; i < menus.length; i++) {
MenuComponent mc = new MenuComponent();
Map row = menus[i];
String name = (String) row.get("name");
mc.setName(name);
String parent = (String) row.get("parent_name");
System.out.println(name + ", parent is: " + parent);
if (parent != null) {
MenuComponent parentMenu = repository.getMenu(parent);
if (parentMenu == null) {
System.out.println("parentMenu '" + parent + "' doesn't exist!");
// create a temporary parentMenu
parentMenu = new MenuComponent();
parentMenu.setName(parent);
repository.addMenu(parentMenu);
}

mc.setParent(parentMenu);
}
String title = (String) row.get("title");
mc.setTitle(title);
String location = (String) row.get("location");
mc.setLocation(location);
String description = (String) row.get("description");
mc.setDescription(description);
repository.addMenu(mc);
}

request.setAttribute("examplesRepository", repository);
}

/**
* 從資料庫中讀取選單配置資訊
*
* @return
*/
private Map[] getMenuComponents() {
ArrayList list = new ArrayList();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rest = null;
String sql = "select name,parent_name,title,location,description from menu_item order by id";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/myexamples?user=root&password=mywangya&useUnicode=true&characterEncoding=UTF-8");
pstmt = conn.prepareStatement(sql);
rest = pstmt.executeQuery();
while (rest.next()) {
int i = 1;
HashMap map = new HashMap();
map.put("name", rest.getString(i++));
map.put("parent_name", rest.getString(i++));
map.put("title", rest.getString(i++));
map.put("location", rest.getString(i++));
map.put("description", rest.getString(i++));
list.add(map);
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (null!=rest) rest.close();
if (null!=pstmt) pstmt.close();
if (null!=conn) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

return (Map[]) list.toArray(new HashMap[0]);
}

/**
* 構造選單許可權
*
* @param request
*/
private void buildMenuPermissions(HttpServletRequest request) {
PermissionsAdapter permession = new PermissionsAdapter() {
public boolean isAllowed(MenuComponent menu) {
// 名稱等於StandaloneMenu的選單不顯示
return !"StandaloneMenu".equalsIgnoreCase(menu.getName());
}
};
request.setAttribute("examplesPermession", permession);
}

/**
* 構造選單顯示標題
*
* @param request
*/
private void buildMenuResourceBundle(HttpServletRequest request) {
MenuResourceBundle resourceBundle = new MenuResourceBundle();
request.setAttribute("examplesBundle", resourceBundle);
}

/**
* MenuResourceBundle樹狀選單國際語言顯示
*
* @author wenbin.zhang
*
*/
class MenuResourceBundle extends ListResourceBundle {
private ArrayList list = new ArrayList();

public MenuResourceBundle() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rest = null;
String sql = "select title,titleCN from menu_item order by id";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/myexamples?user=root&password=mywangya&useUnicode=true&characterEncoding=UTF-8");
pstmt = conn.prepareStatement(sql);
rest = pstmt.executeQuery();
while (rest.next()) {
int i = 1;
String[] message = new String[2];
message[0] = rest.getString(i++);
try {
message[1] = new String(rest.getString(i++).getBytes("latin1"), "gbk");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (message[0] != null && message[1] != null) {
list.add(message);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (null!=rest) rest.close();
if (null!=pstmt) pstmt.close();
if (null!=conn) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}

public Object[][] getContents() {
return (String[][]) list.toArray(new String[0][0]);
}
}
}

> 將struts-config.xml檔案的部分修改為:





> 新建JSP檔案web/dynamic-menu.jsp,內容如下:

沒有使用Bundle和許可權控制:



使用Bundle, 沒有使用許可權控制:



使用Bundle和許可權控制:




重起Tomcat,在位址列輸入
[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750220/viewspace-897740/,如需轉載,請註明出處,否則將追究法律責任。