Programming__WebObjects-Web Applications-Development-Examples-Login
Simple Login
Here is a little example on how to redirect a request to a "login" page if necessary:
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()andWOContext.setCurrentComponent()areundocumentedmethods,butarerequiredinordertoupdatetheWOContextwiththecurrentpageandcomponentinformation.
TheLoginPageclass(notshown)willdecideifaloginisnecessaryornot.
AvoidingSessionTimeoutsatLogin
Agoodloginshouldnottimeoutwhennouserisloggedin.Thiscanbeaproblemifyourapplicationusesasessioninthepagegeneration.
FortunatelyApplehasprovideduswithawayofdoingthiscorrectly:"DirectAction";.YoushouldimplementyourloginpageasaDirectActionandbeverycarefulnottocreatea"lazy"sessionotherwiseyouwillhaveworkedfornothing.WOcreateasessionwhenyoucallcertainmethodssoyouhavetobecareful.Usethis.context().hasSession()tocheckthateverythingisOK.Aftersuccessfulloginyoucreateasessionbycallingthis.session()inyourcomponentandstoretheuserinit;youareinbusiness.
Onlogoutyoudestroythesessionandreturnthedirectactionpagethatwaytheuserhasanewloginscreeninsteadofanemptyscreen.Theeasiestwayofgeneratingaloginpageonlogoutistoreturnaredirectpage(302)tothemainURLoftheapplicationitistransparenttotheuseranddoesexactlywhatyouneed.
Youwillfindthecodesamplethereafter.IplaceitintheApplicationandwhenIwanttologoutIjustcallhandleLogoutwiththecontext.
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;
}
Category:WebObjects