




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、Best practices for Struts developmentPalaniyappan Thiagarajan, Pagadala SureshStruts: A brief introductionStruts, an open source framework you can use to build Web applications, is based on the popular Model-View-Controller (MVC2) design paradigm. The framework is built upon standard technologies li
2、ke Java Servlets, JavaBeans, ResourceBundles, and XML, and it provides flexible and extensible components. Struts implements the Controller layer in the form of ActionServlet and recommends building the View layer using JSP tag libraries. Struts also provides a wrapper around the Model lay
3、er throughAction classes. Figure 1 illustrates the Struts framework based on the Model-View-Controller design.Figure 1. Struts and MVC Overview of Struts componentsFirst, we'll explain the Struts components in the context of best practices and the role each one plays in your Web applic
4、ation development.ActionEvery Action of your application extends Struts' . These Action classes provide an interface to the application's Model layer, acting as a wrapper around the business logic. Each Action class must provide its case-specific implementa
5、tion to the perform() method. The perform() method always returns a value of type ActionForward.ActionFormEvery ActionForm of your application extends Struts' . ActionForms are simple JavaBeans that encapsulate and validate request parameters. To vali
6、date your request data, your ActionForm's validate() method must give a case-specific implementation. ActionForms serve as a carrier of request data to the Action class. A JSP object combines with a respective ActionForm to form your application's View
7、 layer, where almost every form field of the JSP object maps to an attribute of the corresponding ActionForm.JSP custom tag librariesThe JSP custom tag libraries are a collection of actions presented as tags. This is a powerful feature of the JSP Specification 1.1; it allows you to separate pre
8、sentation from other application tiers. The libraries are easy to use and you can read them in XML-like fashion. You can easily maintain the JSP components by minimizing the use of Java scriptlets in them. The JSP tags that Struts provides include HTML, logic, and bean tags.ActionErrorsYou use
9、ActionErrors to support exception handling. An ActionError traps and propagates an application exception to the View layer. Each one is a collection of ActionError instances. ActionErrors encapsulate error messages, while the </html:errors> in the Presentatio
10、n layer renders all error messages in the ActionError collection.Best Practice 1. Reuse data across multiple ActionFormsNow that you are familiar with the Struts components, we will continue by showing you ways to get the most out of the framework. First, Struts recommends that you associa
11、te every JSP object with an ActionForm, which encapsulates data represented in the screen. You access the form data in the JSP object using accessory methods found in ActionForm. Listing 1 shows the conventional use of ActionForm tag in the View layer.Listing 1. Using ActionForm
12、in JSP<html:form action="/bp1"> <html:text property="attrib1" /> </html:form >The ActionForm called "BP1AForm" includes the attribute attrib1, as well as its getter and setter methods. In the configuration file, the action "/bp1&quo
13、t; maps to bp1AForm using the name attribute. This facilitates data display in the JSP.To implement this best practice, Struts recommends you do two things:1. Create a JavaBean (BP1BForm) with attributes that form an attribute subset in BP1AForm, along with the attributes
14、9; getter and setter methods.2. Replace the attributes in BP1AForm with the bean BP1BForm by associating the bean with BP1AForm. Now you can access this attribute subset in BP1AForm through BP1BForm. Listing 2 shows you how.Listing 2. Accessing form attributes
15、 in JSP<html:form action="/bp1"> <bean:define name="bp1AForm" property="bp1BForm" id="bp1B" type="com.ibm.dw.webarch.struts.BP1BForm" /> <html:text name="bp1B" property="subsetAtt1" /> </html:form >Best Pra
16、ctice 2. Use Action class to handle requestsTypically when using the Struts framework, for every action the JSP component requests your application to execute, the application must extend Struts' to create an Action class. This individual Action class interfaces wi
17、th the application's Model layer while processing the request.To implement this practice, Struts recommends you follow these steps:1. Create an Action class, say BP2Action, by extending .2. Create all other Action classes in your Web application by extending BP
18、2Action.3. In BP2Action, create a method performTask(), as in public abstract ActionForward performTask(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) throws IOException, ServletException.4. In BP2Action add one or more generic meth
19、ods to the application, for example serverSideValidate(). You can decide on the method's access modifier by considering the following factors:o If all Action classes must implement this method, make it abstract.o If some Action classes will provide a case-specific implem
20、entation, declare the method protected and give it a default implementation.5. In BP2Action, declare method perform() as final. Invoke the above generic method, which must always be called before processing the request. Now call the method performTask() created in step
21、3.6. In every Action class extending BP2Action, add method performTask() with a case-specific implementation.AdvantagesThis practice has two main advantages. First, it helps you avoid redundant code in every Action class of your Web application. Second, it gives th
22、e application more control over generic tasks by centralizing the behavior in one Action class.Best Practice 3. Use ActionForm to work on session dataIn a Struts-based Web application, each ActionForm extends . These ActionForms encapsulate page data and provide a valid
23、ation framework to validate request parameters.Most Web applications maintain data in session to make them available throughout the application. This best practice addresses this Web application feature. It allows methods toSession() and fromSession() to move session data to and
24、from the form data. Thus, it addresses session data maintenance in a Web application.To adhere to this practice, follow these steps:1. Create an abstract class named BP3Form by extending .2. In BP3Form, add methods with access modifiers as in public abstract void toSession(S
25、essionData sessionData) and void fromSession(SessionData sessionData).3. In every ActionForm, extend BP3Form and implement the abstract methods in which the form data is transported to and from the session.4. The corresponding Action class may determine the order i
26、n which these methods are called. For example, you could invoke method toSession() on the ActionForm just before actionForward is determined.When to use this practiceThis practice is most useful when session data is maintained as a single object and/or every page manipu
27、lates or uses session data.Best Practice 4. Handle exceptions effectivelyConventionally, when an application exception occurs in an Action class, the exception is first logged. Then the class creates anActionError and stores it in the appropriate scope. This Action class the
28、n forwards control to the appropriate ActionForward. Listing 3 shows how Action class handles exceptions.Listing 3. Exception handling in an Action class try /Code in Action class catch (ApplicationException e) /log exception ActionErrors actionErrors = new ActionErrors(); ActionError
29、 actionError = new ActionError(e.getErrorCode(); actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError); saveErrors(request, actionErrors); While conventional exception handling procedures save exception information in every Action class, best practice 4 aims to avoid redundant code whil
30、e handling exceptions.To use this practice, Struts recommends following these steps:1. Create an Action class, say BP4Action, by extending .2. Create all other Action classes in your Web application by extending BP4Action.3. In BP4Action, declare variable
31、;ActionErrors actionErrors = new ActionErrors();.4. In BP4Action, create a method performTask() as in public abstract ActionForward performTask(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response, ActionErrors actionErrors) throws IOException,
32、 ServletException.5. In BP4Action, declare method perform() as final. Then invoke generic methods, which must always be called before processing the request. Now you can call the method performTask() created in the previous step.6. While implementing method performTask(
33、) in every Action class (by extending BP4Action), handle application exceptions as shown in Listing 4.Listing 4. Using ActionErrors effectively try /Code in Action class catch(ApplicationException appException) /Log exception /Add error to actionErrors actionErrors.add(ActionErro
34、rs.GLOBAL_ERROR, new ActionError(appException.getErrorCode(); In BP4Action, after invoking the method performTask(), save the ActionErrors using saveErrors(request, errors).AdvantagesThis practice's main advantage is that it avoids code redundancy in every Action
35、60;class that handles ActionErrors.In conclusionBuilding an easily maintainable Web application can be one of the most challenging tasks for a development team. Using a mature framework like Struts helps you implement the infrastructure code normally associated with building an application. The
36、 Struts framework provides a set of standard interfaces for plugging business logic into the application, a consistent mechanism across development teams for performing tasks such as user data validation, screen navigation, and so forth, as well as a set of custom tag libraries to simplify developin
37、g screens.These four best practices are important for you to extract more from the framework's features. You, as a developer, can benefit from these lessons to increase your code modularity and application reusability, plus minimize code redundancy. These are all critical to building an extensib
38、le Web application.譯文Struts 開發(fā)的最佳實踐Palaniyappan Thiagarajan, Pagadala SureshStruts:簡介Struts 是一種開源框架,可用來構建 Web 應用程序,它基于流行的 Model-View-Controller (MVC2) 設計范型。該框架構建在一些標準的技術之上,比如 Java Servlets、JavaBeans、ResourceBundles 和 XML,并且可提供靈活和可擴展的組件。Struts 以ActionServlet 的形式實現了 Controller 層,并建議使用 JSP 標記庫構建 V
39、iew 層。Struts 通過 Action 類提供了圍繞 Model 層的包裝器。圖 1 展示了基于 Model-View-Controller 設計的 Struts 框架。圖 1. Struts 和 MVC Struts 組件概覽首先,我們在最佳實踐上下文中解釋 Struts 組件,以及它們在 Web 應用程序開發(fā)中所起的作用。Action應用程序的每個 Action 都會擴展 Struts 的 類。這些 Action 類為應用程序的 Model 層提供了一個接口,充當圍繞業(yè)務邏輯的包裝器。每個
40、160;Action 類都必須向 perform() 方法提供其特定于用例的實現。perform() 方法經常返回類型 ActionForward 的一個值。ActionForm應用程序的 ActionForm 擴展了 Struts 的 類。ActionForm 是一些封裝和驗證請求參數的簡單 JavaBean。要驗證請求數據,ActionForm 的 validate() 方法必須給出一個特定于該情況的實現。ActionForm 作為運載工具
41、,向Action 類提供請求數據。一個 JSP 對象與各自的 ActionForm 對象相結合,構成應用程序的 View 層。在該層,幾乎 JSP 對象的每個表單字段都映射到相應的 ActionForm 的屬性。JSP 定制標記庫JSP 定制標記庫是用標記表示的一組行為的集合。這是 JSP Specification 1.1 的一個強大特性;它將其他應用程序層的表示區(qū)別了開來。這些庫易于使用,而且可以以一種類似 XML 的方式來讀取。只要盡量少地在其中使用 Java scriptlet,就可以輕松維護 JSP 組件。Struts 提供的 JSP
42、 標記包括 HTML、邏輯和 bean 標記。ActionErrors可以使用 ActionError 來支持異常處理。ActionError 捕捉應用程序異常,并將其傳送給 View 層。每個異常都是一個 ActionError實例的集合。ActionError 可以封裝錯誤消息,而 Presentation 層中的 </html:errors> 可以呈現 ActionError 集合內的所有錯誤消息。最佳實踐 1. 跨多個 ActionForm 重用數據熟悉了 Struts 組件之后,就可
43、以繼續(xù)學習如何充分利用這一框架。首先,Struts 建議將每個 JSP 對象與一個 ActionForm 相關聯,后者可以封裝屏幕上顯示的數據??梢酝ㄟ^ ActionForm 內的附加方法來訪問 JSP 對象內的表單數據。清單 1 展示了 ActionForm 標記在 View 層中的傳統(tǒng)方法。清單 1. 使用 ActionForm<html:form action="/bp1"> <html:text property="attrib1" /> </html:fo
44、rm >這個 ActionForm 被稱為 “BP1AForm”,它包括屬性 attrib1 及其 getter 和 setter 方法。在配置文件 s 中,行為 “/bp1” 通過 name 屬性映射到 bp1AForm。這有助于在 JSP 中顯示數據。要實現這一最佳實踐,Struts 建議您進行以下兩個操作:1. 創(chuàng)建一個 JavaBean(BP1BForm),且其屬性是 BP1AForm 屬性的子集,還要創(chuàng)建這些屬性的 getter 和 setter 方法。2. 通過將這個
45、 bean 與 BP1AForm 關聯,用 bean BP1BForm 的屬性替代 BP1AForm 中的屬性?,F在就可以通過 BP1BForm 訪問BP1AForm 中的屬性子集了。清單 2 展示了訪問的方式。清單 2. 訪問 JSP 中的表單屬性 <html:form action="/bp1"> <bean:define name="bp1AForm" property="bp1BForm" id="bp1B&q
46、uot;.dw.webarch.struts.BP1BForm" /> <html:text name="bp1B" property="subsetAtt1" /> </html:form >最佳實踐 2. 使用 Action 類處理請求通常,在使用這個 Struts 框架時,對于 JSP 組件請求應用程序執(zhí)行的每個動作,應用程序都必須擴展 Struts 的 以創(chuàng)建 Action 類。在處理請求時,單個的 Action 類與應用程序的 Model 層連接。要實現這
47、一最佳實踐,Struts 建議您遵循以下步驟:1. 通過擴展 創(chuàng)建一個 Action 類,比如 BP2Action。2. 通過擴展 BP2Action 在 Web 應用程序中創(chuàng)建所有其他 Action 類。3. 在 BP2Action 類中創(chuàng)建一個方法 performTask(),就像在公共抽象類 ActionForward performTask(ActionMapping mapping, ActionForm form, ServletRequest req
48、uest, ServletResponse response) throws IOException, ServletException 中一樣。4. 在 BP2Action 類中向應用程序添加一個或多個泛型方法,比如 serverSideValidate()??紤]以下因素后決定方法的訪問修飾符:o 如果所有 Action 類都必須實現此方法,則讓其為抽象。o 如果某些 Action 類提供一個特定的實現,則將此方法聲明為受保護,并給它一個默認實現。5. 在 BP2Action 類中,將方法
49、160;perform() 聲明為 final。調用上述的泛型方法(通常在處理請求前調用該方法)?,F在調用 步驟 3 中創(chuàng)建的方法 performTask()。6. 在每個擴展 BP2Action 的 Action 類,添加具有特定實現的方法 performTask()。優(yōu)勢這一實踐有兩個主要優(yōu)勢。首先,它避免了 Web 應用程序中每個 Action 類的冗余代碼。其次,通過將 Action 類的行為集中在一起,使應用程序能夠更多地控制通用的任務。最佳實踐 3. 使
50、用 ActionForm 處理會話數據在一個基于 Struts 的 Web 應用程序中,每個 ActionForm 都擴展 類。這些 ActionForm 封裝頁面數據,并提供一個驗證框架來驗證請求參數。大多數 Web 應用程序都在會話中保持數據,使其在整個應用程序過程中可用。這種最佳實踐實現了這種 Web 應用程序特性。它允許方法 toSession() 和 fromSession() 將會話數據移動到表單數據或從表單數據移回。因此,它實現了在 Web 應用程序中保持會話數據。要遵循一最佳實
51、踐,執(zhí)行以下步驟:1. 通過擴展 創(chuàng)建一個名為 BP3Form 的抽象類。2. 在 BP3Form 類中,添加具有訪問修飾語的方法,就像在公共抽象類 void toSession(SessionData sessionData) 和 void fromSession(SessionData sessionData) 中一樣。3. 在每個 ActionForm 類中,擴展 BP3Form 并實現這些抽象方法(表單數據通過它們傳遞到會話或從會話傳回)。4.
52、相應的 Action 類可以決定這些方法的調用順序。例如,可以在決定 actionForward 之前調用 ActionForm 上的方法toSession()。何時使用這一實踐這一實踐最適用于:會話數據是單一對象和/或每個頁操作或使用會話數據。最佳實踐 4. 有效處理異常傳統(tǒng)地,當在 Action 類中發(fā)生應用程序異常時,異常首先被寫入日志。然后此類創(chuàng)建一個 ActionError 并在合適的作用域中存儲它。然后 Action 類再將控制轉交給合適的 Action
53、Forward。清單 3 展示了 Action 類是如何處理異常的。清單 3. Action 類中的異常處理 try /Code in Action class catch (ApplicationException e) /log exception ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError(e.getErrorCode(); actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError
54、); saveErrors(request, actionErrors); 傳統(tǒng)的異常處理過程在每個 Action 類中保存異常信息,而最佳實踐 4 則在處理異常時避免冗余代碼。要使用這一最佳實踐,Struts 建議您遵循以下步驟:1. 通過擴展 創(chuàng)建一個 Action 類,比如 BP4Action。2. 通過擴展 BP4Action 在 Web 應用程序中創(chuàng)建所有其他 Action 類。3. 在 BP4Action 中聲明變量 ActionErrors
55、 actionErrors = new ActionErrors();。4. 在 BP4Action 中創(chuàng)建方法 performTask(),就像在公共抽象類 ActionForward performTask(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response, ActionErrors actionErrors) throws IOException, ServletException 中一樣。5. 在 B
56、P4Action 中將方法 perform() 聲明為 final。然后調用泛型方法(這些方法總是在處理請求前調用)。現在調用在前一個步驟中創(chuàng)建的 performTask()。6. 在每個 Action 類中實現方法 performTask() 的同時(通過擴展 BP4Action),像清單 4 那樣處理應用程序異常。清單 4. 有效使用 ActionErrors try /Code in Action class catch(ApplicationException appException) /Log
57、 exception /Add error to actionErrors actionErrors.add(ActionErrors.GLOBAL_ERROR, new ActionError(appException.getErrorCode(); 在 BP4Action 中,調用方法 performTask() 之后,通過 saveErrors(request, errors) 保存 ActionErrors。優(yōu)勢這一實踐主要的優(yōu)勢是:避免了每個處理 ActionErrors 的 Acti
58、on 類中的代碼冗余。結束語對開發(fā)團隊而言,構建易于維護的 Web 應用程序是一項非常具有挑戰(zhàn)性的任務。使用 Struts 等成熟的框架有助于實現通常與構建應用程序相關的基礎設施代碼。Struts 框架提供了一組標準接口,用于將業(yè)務邏輯插入到應用程序中。此外,還提供了一種跨開發(fā)團隊的一致機制,用于執(zhí)行用戶數據驗證、屏幕導航等任務,以及用于簡化開發(fā)屏幕的一組定制標記庫。本文給出的 4 種最佳實踐對您充分利用這種框架的特性十分重要。它們不僅能夠提高代碼的模塊化程度和應用程序的可重用性,還能減少代碼冗余。對于構建可擴展的 Web 應用程序,這是至關重要的。本文譯自: developerWorksWeb development
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 山東大學《書法藝術》2023-2024學年第一學期期末試卷
- 文化傳媒員工招聘管理制度及工作流程
- SA公司基層技術人員績效考核體系改進研究
- 木材衍生高性能電化學二氧化碳還原催化劑的制備及其電催化性能研究
- 投針實驗戶外活動方案
- 教室配音活動策劃方案
- 打造戶外活動方案
- 教育培訓市場活動方案
- 教師暑期培訓活動方案
- 黑龍江省鄉(xiāng)鎮(zhèn)社工站的內生能力的服務模式研究
- 2025年黑龍江省龍東地區(qū)中考數學試卷真題(含答案)
- 2025年建筑電氣工程師職業(yè)資格考試試卷及答案
- 2025年中小學暑假安全教育主題家長會 課件
- 房地產銷售計劃書
- 2025年勞動爭議仲裁員(二級)考試試卷
- 空中安全保衛(wèi)課件
- 2024年全市首屆檔案職業(yè)技能競賽考試題庫(含答案)
- 2025年沈陽水務集團有限公司-企業(yè)報告(代理機構版)
- 近視管理白皮書(2025)專家共識-
- 數字化藝術-終結性考核-國開(SC)-參考資料
- 2025年佛山市南海區(qū)圖書館招聘題庫帶答案分析
評論
0/150
提交評論