Are parameters of TWebModule event handlers global?
I'm using the TWebModule component to write a web server application with Delphi. Clicking on the Actions property of the TWebModule a new action can be defined and a "OnAction" event handler created. For example:
procedure TMainWeb.MyAction(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
Response.Content := '<html><body>myvariab开发者_运维技巧le: '+request.queryfields.values['myvariable']+</body></html>';
end;
I have noticed non-parametered procedures can be called which have access to the TWebModule's Request, Response, and Handled parameters. For instance, I have successfully used the following instead of explicitly created action handlers:
procedure TMainWeb.WebModuleBeforeDispatch(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
if Pos('myaction.html',request.url)>0 then
DoMyAction;
end;
procedure TMainWeb.DoMyAction;
begin
Response.Content := '<html><body>myvariable: '+request.queryfields.values['myvariable']+</body></html>';
end;
Can I always be assured the references to Sender, Request, Response, and Handled I make in DoMyAction are the "correct" ones?
No, you can't be assured of that in all cases and you're preparing a maintenance nightmare.
Why don't you create a DoMyAction that takes as parameters whatever you need inside from Request, Response and Handled?
With your example it would become:
procedure TMainWeb.WebModuleBeforeDispatch(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
if Pos('myaction.html',request.url)>0 then
begin
DoMyAction(Request, Response);
Handled := True;
end;
end;
procedure TMainWeb.DoMyAction(ARequest: TWebRequest; AResponse: TWebResponse);
begin
AResponse.Content := '<html><body>myvariable: '+ARequest.queryfields.values['myvariable']+</body></html>';
end;
A TWebModule instance is created (or grabbed from a pre-allocated pool) for each request as it is processed. The Request and Response are available as properties on the instance. As long as you don't go trying to access another TWebModule instance, the Request/Response properties will be valid through out the lifetime of the request. If you call other methods on the TWebModule, you don't have to qualify their use. If you intend to have them accessible to other object methods or global procedures/functions, you need to pass them along as parameters.
精彩评论