program routingsessiondemo; {$mode objfpc}{$H+} uses SysUtils, fphttpapp, // Standaline fphttp, // Session manager iniwebsession, // Ini based sessions httpdefs, // TRequest,TResponse httproute; {$IFDEF VER3_0} Type { TSessionState } TSessionState = Class(TObject) IsNew : Boolean; IsExpired : Boolean; Procedure OnNew(Sender : TObject); Procedure OnExpired(Sender : TObject); end; procedure TSessionState.OnNew(Sender: TObject); begin IsNew:=True; end; procedure TSessionState.OnExpired(Sender: TObject); begin IsExpired:=True; end; {$ENDIF} Procedure DisplayForm(aResponse : TResponse); begin With AResponse.Contents do begin Add('
'); Add('
'); Add('Start new session
'); Add('End the session'); end; end; Procedure DisplayNewSession(aResponse : TResponse; aSession : TCustomSession); Var C : TCookie; begin With AResponse.Contents do begin Add('
'); {$ENDIF} Add('A new session was started.
');
C:=AResponse.Cookies.FindCookie(aSession.SessionCookie);
If Assigned(C) then
begin
Add('The issued session cookie is called '+C.Name+'.
');
Add('The issued session cookie has value '+C.Value+'.
');
end
else
Add('No session cookie was found.');
DisplayForm(AResponse);
Add('');
end;
end;
Procedure NewSession(aRequest : TRequest; aResponse : TResponse);
Var
Session : TCustomSession;
begin
Session:=SessionFactory.CreateSession(aRequest);
try
Session.InitSession(aRequest,Nil,Nil);
Session.InitResponse(aResponse);
DisplayNewSession(aResponse,Session);
Finally
Session.Free;
end;
end;
Procedure EndSession(aRequest : TRequest; aResponse : TResponse);
Var
Session : TCustomSession;
begin
Session:=SessionFactory.CreateSession(aRequest);
try
Session.InitSession(aRequest,Nil,Nil);
// Stop the session
Session.Terminate;
Session.InitResponse(aResponse);
With AResponse.Contents do
begin
Add('
');
// If Session is TFPWebSession then
begin
C:=AResponse.Cookies.FindCookie(Session.SessionCookie);
If Assigned(C) then
begin
Add('Current session Cookie is called '+C.Name+'
');
Add('and has value '+C.Value+'.');
end;
V:=Session.Variables['Var'];
If (V<>'') then
Add('
Stored session value: '+V+'.') else Add('
No values stored in session.'); V:=ARequest.QueryFields.Values['Var']; If V<>'' then begin Add('
Storing new session value: '+V+'.'); Session.Variables['Var']:=V; end; end; DisplayForm(AResponse); Add(''); AResponse.SendContent; // Handles the response. end; finally {$IFDEF VER3_0} State.Free; {$ENDIF} Session.Free; end; end; begin HTTPRouter.RegisterRoute('/insession',@InSession); HTTPRouter.RegisterRoute('/endsession',@EndSession); HTTPRouter.RegisterRoute('/newsession',@NewSession,True); if ParamCount=1 then Application.Port:=StrToIntDef(ParamStr(1),8080) else Application.Port:=8080; Writeln('Server listens on port : ',Application.Port); Application.Initialize; Application.Run; end.