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;
}