JSP設計模式中的兩種常見模式
如果你經常去Servlet或JSP的新聞組或者郵件列表,那么一定會看到不少關于Model I 和Model II 方法的討論。究竟采用哪一種,這取決于你的個人喜好、團隊工作策略以及是否采用正統的OOP。
簡單地說,Model I將事務邏輯(business logic)和表示代碼(presentation code)融合在一起(如在HTML中);Model II則提倡最大限度地將所有的代碼放到內容表示之外。
Model I: 簡單的單層次應用
如果是在一個人人都精通Java和HTML的環境中,或者你獨自做著所有的工作,假如每個人都有清晰的編程結構和思路,那么這種方法會很有效,不過這樣的假設不在本文討論范圍之內。這種方法的第一個優點是如果你的應用改變了,你只需維護一個文件。而最大的缺陷是可讀性!除非十分小心,否則你的HTML和Java代碼會相互混雜,從而難以維護。
在下面這個例子中,我們將增加一個 TimeZone 元素,從而使它變成JSP文件,它會返回基于時間的所期待的TimeZone。如果沒有提交 TimeZone,那么缺省的是服務器的缺省時間。
- ======================================================================
- ﹤xml version=“1.0“ ?﹥
- ﹤H1﹥Time JSP﹤/H1﹥
- ﹤jsp:scriptlet﹥
- //the parameter “zone“ shall be equal to a number between 0 and 24 (inclusive)
- TimeZone timeZone = TimeZone.getDefault(); //returns the default TimeZone for the server
- if (request.getParameterValues(“zone“) != null)
- {
- String timeZoneArg = request.getParameterValues(“zone“)[0];
- timeZone = TimeZone.getTimeZone(“GMT+“ + timeZoneArg + “:00“);
- // gets a TimeZone. For this example we´re just going to assume
- // its a positive argument, not a negative one.
- }
- //since we´re basing our time from GMT, we´ll set our Locale to Brittania, and get a Calendar.
- Calendar myCalendar = Calendar.getInstance(timeZone, Locale.UK);
- ﹤/jsp:scriptlet﹥
- ﹤%= myCalendar.get(Calendar.HOUR_OF_DAY) %﹥:
- ﹤%= myCalendar.get(Calendar.MINUTE) %﹥:
- ﹤%= myCalendar.get(Calendar.SECOND) %﹥
- ======================================================================
相應地,數據也可以從JavaBean取得并加以顯示。在下一個例子中我們就可以看到。
Model II: 重定向請求(Redirecting Requests)
在一個團隊開發環境中,有些是HTML設計者,另一些則是Java程序員,這時這一方法顯得非常重要。Java程序員可以集中精力創建可重用代碼,而HTML設計師可以集中精力于內容表示,彼此相對對立,可以分別動態地修改自己的內容,只要總體的輸入輸出不變。
現在我們可以使用Model II來表示Model I的那個例子。這一方法遵循了Model-View-Controller (MVC) 范例 (cite Design Patterns book)。 在這個例子中,我們只有一個類(頁或者servlet) 處理請求(Controller),取得TimeZone,設置所有用于表示的變量,并將控制傳遞到表示頁(View)。作為如此簡單的應用,可以沒有 “Model“。
Controller: timeByZone.jsp
controller可以是一個servlet或一個JSP頁。我推薦使用JSP,因為這樣我不必擔心每當我做修改時要對類重新編譯,但是,你將因此失去granularity(顆粒性),以后要擴展該類也比較困難。
- ======================================================================
- ﹤xml version=“1.0“ ?﹥
- ﹤!--Worker Class, nobody should see me--﹥
- ﹤jsp:scriptlet﹥
- //the parameter “zone“ shall be equal to a number between 0 and 24 (inclusive)
- TimeZone timeZone = TimeZone.getDefault(); //returns the default TimeZone for the server
- if (request.getParameterValues(“zone“) != null)
- {
- String timeZoneArg = request.getParameterValues(“zone“)[0];
- timeZone = TimeZone.getTimeZone(“GMT+“ + timeZoneArg + “:00“);
- // gets a TimeZone. For this example we´re just going to assume
- // its a positive argument, not a negative one.
- }
- TimeBean timeBean = new TimeBean();
- timeBean.setHours = myCalendar.get(Calendar.HOUR_OF_DAY);
- timeBean.setMinutes = myCalendar.get(Calendar.MINUTE);
- timeBean.setSeconds = myCalendar.get(Calendar.SECOND);
- HttpSession mySession = request.getSession();
- mySession.putValue(“tempTimeBean“, timeBean);
- ﹤/jsp:scriptlet﹥
- ﹤jsp:forward page=“displayTime.jsp“ /﹥
- ======================================================================
View: displayTime.jsp
同樣地,這個view既可以是一個servlet也可以是一個jsp文件。這里我們從Session中取得并顯示它的值。實際上我們會將這做兩次,來示范Bean是如何被使用的。
- ======================================================================
- ﹤xml version=“1.0“ ?﹥
- ﹤H1﹥Time JSP﹤/H1﹥
- ﹤jsp:useBean class=“TimeBean“ id=“tempTimeBean“ scope=“session“ /﹥
- ﹤jsp:getProperty name=“tempTimeBean“ property=“hours“﹥:
- ﹤jsp:getProperty name=“tempTimeBean“ property=“minutes“﹥:
- ﹤jsp:getProperty name=“tempTimeBean“ property=“seconds“﹥
- ﹤!-- these would have printed “null“ if tempTimeBean was not instantiated by timeByZone.jsp --﹥
- ﹤jsp:scriptlet﹥
- HttpSession mySession = request.getSession();
- TimeBean timeBean = mySession.getValue(“tempTimeBean“);
- if (timeBean != null)
- { // check to make sure its not null, to avoid NullPointerExceptions
- out.print(timeBean.getHours());
- out.print(“:“);
- out.print(timeBean.getMinutes());
- out.print(“:“);
- out.print(timeBean.getSeconds());
- }
- else
- {
- out.println(“Press your Back button and select a TimeZone“);
- }
- ﹤/jsp:scriptlet﹥
- ======================================================================
第二種方法(在內部使用了代碼)可能有些笨重,但允許開發者確保輸出不至于很糟糕(例如“null:null:null null“),假定Session bean還沒有被實例化以及沒有進行值的設置。 這種情況發生在客戶端直接調用了View頁。問題是使用腳本scriptlets可以允許更強的控制。如果你確信你可以控制url存取,那么bean方法當然更適合于開發,并使 View頁更方便于HTML設計者的協同工作。
上面的是“傳統的“ Model II設計。所有的變量都包裝了并放在Session對象中。這有2個不足:
1) 如果客戶端拒絕參與的話,Session是不可得到的。
2) 除非Session變量被顯式地移走,否則它回一直存在,直到Session被破壞或過期。
第一種案例很可能發生在這樣的場合,即使用了cookies作為聲明的結構(mechanism)而開發者沒有能夠提供聲明的結構的替代表單(form),即URL改寫。
第二個案例甚至更為嚴重,因為它可能引起很大的內存消耗,如果Sessions被定義為保存比標準存留時間更長的話((標準存留時間是30分鐘)。即使是30分鐘的Session,這種Model也可能在大的應用中引起災難性的內存泄露。為什么呢?在Session對象內部設置的對象被實例化了,并且在Session終止以前一直沒有被移去。因為它們仍然有關聯references(Session對象) 指向它們,所以無法被垃圾收集(garbage-collected)。
在Model II 模型中,很多對象被放到Session中(要么直接地,要么通過JavaBean)。隨著Session的進行,更多的頁被存取,內存使用會增加并持續下去直到客戶端終止了Session或者Session過期。要一直等到Session變得非法,放在那的對象才能被垃圾收集,而那些損失的內存本可以用于任何其它的用途。.
改進的方法之一是將Beans或者其它變量放到Request對象中去,并使用RequestDispatcher.include()而不是RequestDispatcher.forward()。這樣做以后,View 頁具有和Controller一樣的存取請求的對象。傳統的Model II設計的不足可以被排除。
一個最后的評注:盡管有如上所述,我個人仍有些不喜歡Model II 的范例,如果它用通常方法開發的話。 客戶端被引送到某一個地址,然后又被轉向到另一個不同的類,我不喜歡創建這樣的系統?;谶@樣的原因,我修改了設計,使它變成了以下的樣子:
Controller: timeByZone2.jsp
和前面一樣,controller使用Request值來取得必要的數據,并且將數據放到請求的對象中去。這回的區別是View頁將使用RequestDispatcher.include()來調用Controller。在這種方法中,客戶端再也不做重定向,請求不是“鏈接chained”的。相當于class/jsp請求了另一方來為它做一些工作,然后繼續。
- ======================================================================
- ﹤xml version=“1.0“ ?﹥
- ﹤!--Worker Class, nobody should see me--﹥
- ﹤jsp:scriptlet﹥
- //the parameter “zone“ shall be equal to a number between 0 and 24 (inclusive)
- TimeZone timeZone = TimeZone.getDefault(); //returns the default TimeZone for the server
- if (request.getParameterValues(“zone“) != null)
- {
- String timeZoneArg = request.getParameterValues(“zone“)[0];
- timeZone = TimeZone.getTimeZone(“GMT+“ + timeZoneArg + “:00“);
- // gets a TimeZone. For this example we´re just going to assume
- // its a positive argument, not a negative one.
- }
- TimeBean timeBean = new TimeBean();
- timeBean.setHours = myCalendar.get(Calendar.HOUR_OF_DAY);
- timeBean.setMinutes = myCalendar.get(Calendar.MINUTE);
- timeBean.setSeconds = myCalendar.get(Calendar.SECOND);
- request.setAttribute(“tempTimeBean“, timeBean);
- ﹤/jsp:scriptlet﹥
- ======================================================================
View: displayTime2.jsp
和displayTime.jsp非常相似,但timeByZone2.jsp在也的頂部被調用。請注意
在一個在建系統中,我們已經使用這種方法來創建類的鏈,每一個都只對它所處理的工作負責。通過辨別公用的表示格式,我們創建了一個View對象,即使在很高層次的JSP中它也可以重復使用。我們的目標就是建立一些可重用的頁,同時減少用于表示的類的數量
- ======================================================================
- ﹤xml version=“1.0“ ?﹥
- ﹤H1﹥Time JSP﹤/H1﹥
- ﹤jsp:include page=“timeByZone2.jsp“ /﹥
- ﹤jsp:useBean class=“TimeBean“ id=“tempTimeBean“ scope=“request“ /﹥
- ﹤jsp:getProperty name=“tempTimeBean“ property=“hours“﹥:
- ﹤jsp:getProperty name=“tempTimeBean“ property=“minutes“﹥:
- ﹤jsp:getProperty name=“tempTimeBean“ property=“seconds“﹥
- ﹤!-- these would have printed “null“ if tempTimeBean was not instantiated by timeByZone2.jsp --﹥
- ======================================================================
【編輯推薦】