1. Model-View-Controller a. 問題 假如開發一個企業級應用,只需要一種客戶端的話,那么一切都非常輕易解決。但真實情況是,我們必須面對運行在各種設備上客戶端,象PDA,WAP瀏覽器以及運行在桌面上的瀏覽器,我們不得不開發不同的應用程序來處理來自不同客戶端的請求。數據訪問與現實將混淆在一起,可能會出現重復的數據訪問,導致整個開發周期沒有必要的延長。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String currentPage= request.getPathInfo(); // get all mapping info for "currentPage" from the hashmap // if "securityCheckRequired = true", do the security check // if "useRequestHandler = true", pass on the incoming request to the specified handler // forward the results to the given "nextScreen" } } 用這種方法實現的控制器將很輕易維護,當應用有新的變動的時候,只要修改XML文件就能解決了。前臺控制模式將使在視圖和控制器之前有復雜交互的J2EE應用變得簡單。
3. session Facade a. 問題 前臺控制給出了一個基于MVC的,能有效治理用戶與J2EE應用之間進行的復雜交互。這個模式可以使處理頁面的現實順序和用戶的并發請求變得簡單。并且使增加和改變頁面現實變得更加輕易。 另外一個常見的問題是,當EJB或者業務邏輯發生變化的時候,應用的客戶端也必須隨之改變。我們來看一下這個問題。 一般來說,為了表現一個賬戶中的用戶,我們使用一個業務邏輯來表示賬戶中的信息,象用戶名和口令,再用一個EJB來治理用戶的個人信息,象愛好,語言等。當要創建一個新的賬號或者修改一個已經存在的賬號時,必須訪問包含賬號信息的EJB,讀取個人信息,修改并且保存,這樣的一個流程。 當然,這只是一個非常簡單的例子,實際情況可能比這個復雜的多,象查看用戶定制了哪些服務,檢驗客戶信用卡的有效性,存放訂單等。在這個案例中,為了實現一個完整的流程,客戶端必須訪問賬戶EJB來完成一系列適當的工作。下面的例子顯示了一個Servlet客戶端如何來控制一個用戶訂單。 A servlet that does the workflow required for placing an order // all required imports; // exceptions to be caught appropriately wherever applicable; // This servlet assumes that for placing an order the account and // credit status of the customer has to be checked before getting the // approval and committing the order. For simplicity, the EJBs that // represent the business logic of account, credit status etc are // not listed
public class OrderHandlingServlet extends HttpServlet {
// all required declarations, definitions
public void init() { // all inits required done here }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // other logic as required // Get reference to the required EJBs InitialContext ctxt = new InitialContext(); Object obj = ctxt.lookup("java:comp/env/ejb/UserAccount"); UserAccountHome acctHome = (UserAccountHome) PortableRemoteObject.narrow(obj, UserAccountHome.class); UserAccount acct = acctHome.create(); obj = ctxt.lookup("java:comp/env/ejb/CreditCheck"); CreditCheckHome creditCheckHome = (CreditCheckHome) PortableRemoteObject.narrow(obj, CreditCheckHome.class); CreditCheck credit = creditCheckHome.create(); obj = ctxt.lookup("java:comp/env/ejb/Approvals"); ApprovalsHome apprHome = (ApprovalsHome) PortableRemoteObject.narrow(obj, ApprovalsHome.class); Approvals appr = apprHome.create(); obj = ctxt.lookup("java:comp/env/ejb/CommitOrder"); CommitOrderHome orderHome = (CommitOrderHome) PortableRemoteObject.narrow(obj, CommitOrderHome.class); CommitOrder or