跳轉至內容

WebObjects/Web 應用程式/開發/示例/登入

來自華夏公益教科書,開放書籍,開放世界

簡單登入

[編輯 | 編輯原始碼]

這是一個關於如何在必要時將請求重定向到“登入”頁面的示例。

 public void appendToResponse(WOResponse aResponse, WOContext aContext)
 {
   String	aPageName = LoginPage.pageWithContext( aContext );
 
   if ( ( aPageName != null ) && ( this.name().equals( aPageName ) == false ) )
   {
     WOComponent	aComponent = this.pageWithName( aPageName );
 
     this.currentSession().setPage( aPageName );
     aContext._setPageComponent( aComponent );
     aContext._setCurrentComponent( aComponent );
     aComponent.appendToResponse( aResponse, aContext);
 
     return;
   }
 
   this.currentSession().setPage( this.name() );
   super.appendToResponse( aResponse, aContext);
 }

WOContext._setPageComponent() 和 WOContext._setCurrentComponent() 是未公開的方法,但需要用於更新 WOContext 中的當前頁面和元件資訊。

LoginPage 類(未顯示)將決定是否需要登入。

避免登入時的會話超時

[編輯 | 編輯原始碼]

一個好的登入不應該在沒有使用者登入時超時。如果您的應用程式在頁面生成中使用了會話,這可能是一個問題。

幸運的是,蘋果為我們提供了一種正確的方法:“DirectAction”。您應該將您的登入頁面實現為一個 DirectAction,並非常小心地不要建立“延遲”會話,否則您的工作將付諸東流。WO 在您呼叫某些方法時會建立會話,因此您必須小心。使用 this.context().hasSession() 來檢查一切是否正常。登入成功後,您透過在元件中呼叫 this.session() 來建立會話,並將使用者儲存在其中;您就可以開始操作了。

在登出時,您會銷燬會話並返回 direct action 頁面,這樣使用者就會看到一個新的登入螢幕,而不是空白螢幕。登出時生成登入頁面的最簡單方法是返回一個重定向頁面(302)到應用程式的主 URL,對於使用者來說是透明的,並且完全按照您的需要執行。

您可以在此之後找到程式碼示例。我將其放在 Application 中,當我想登出時,只需使用 context 呼叫 handleLogout。

 private WOResponse responseForPageWithName(String aPageName, WOContext aContext) {
   if ( aPageName != null ) {
       WOResponse	aResponse = new WOResponse();
       String adaptorPrefix = aContext.request().adaptorPrefix();
       String applicationName = aContext.request().applicationName();
       String anURL = adaptorPrefix + "/" + applicationName + ".woa";
       aResponse.setHeader(anURL, "Location");
       aResponse.setHeader("text/html", "content-type");
       aResponse.setHeader("0","content-length");
       aResponse.setStatus(302);
       return aResponse;
   }
   return null;
 }
 
 public WOResponse handleLogout(WOContext aContext) {
   WOResponse aResponse = this.responseForPageWithName("Login", aContext);
   if ( ! aContext.session().isTerminating() ) {
       ((Session)aContext.session()).setUser(null);
       aContext.session().terminate();
   }
   return aResponse;
 }
華夏公益教科書