Skip to content

Working with contexts

Michael Justin edited this page May 24, 2025 · 5 revisions

A context represents a logical unit in a web application.

For example, if the web application runs at example.local and uses the contexts 'baz' and 'qux', its resources may located at paths such as

Context creation

The statement Context := TdjWebAppContext.Create('baz'); creates a new context with the context path /baz.

Context registration

The statement Server.Add(Context); registers the context with the server.

Options

Root context

The statement Context := TdjWebAppContext.Create(''); creates a new root context, which has an empty context path.

Session support

The statement Context := TdjWebAppContext.Create('qux', True); creates a new context with the context path qux with automatic session creation enabled.

Code example

procedure Demo;
var
  Server: TdjServer;
  Context: TdjWebAppContext;
begin
  Server := TdjServer.Create(80);
  try
    Context := TdjWebAppContext.Create('tutorial', True);
    Context.Add(TSessionDemoResource, '/session');
    Server.Add(Context);
    Server.Start;
    WriteLn('Server is running, please open http://127.0.0.1/tutorial/session');
    WriteLn('Hit enter to terminate.');
    ReadLn;
  finally
    Server.Free;
  end;
end;

The TSessionDemoResource OnGet method displays the number of requests which it has received from the same session:

procedure TSessionDemoResource.OnGet(Request: TdjRequest; Response: TdjResponse);
var
  RequestCountForSession: string;
begin
  RequestCountForSession := Request.Session.Content.Values['count'];
  if RequestCountForSession = '' then RequestCountForSession := '1';

  Request.Session.Content.Values['count'] :=
    IntToStr(StrToInt(RequestCountForSession) + 1);

  Response.ContentText :=
    Format('Your Session ID is %s ', [Request.Session.SessionID]) + #10 +
    Format('I have received %s GET Requests during this session', [RequestCountForSession]);

  Response.ContentType := 'text/plain';
end;
Clone this wiki locally