WebServer
The WebServer
class API allows you to start and monitor a web server for the main (host) application as well as each hosted component (see the Web Server object overview). This class is available from the 4D
class store.
Web Server object
Web server objects are instantiated with the WEB Server
command.
They provide the following properties and functions:
Resumo
.accessKeyDefined : Boolean
|
.certificateFolder : Text
|
.characterSet : Number .characterSet : Text conjunto de caracteres que o Servidor Web 4D deve usar para se comunicar com navegadores conectados ao aplicativo. The default value actually depends on the language of the OS. Pode ser um inteiro MIBEnum ou uma string de nome, identificadores definidos por IANA. Aqui está a lista de identificadores correspondentes aos conjuntos de caracteres suportados pelo Servidor Web 4D: |
- 4 = ISO-8859-1
- 12 = ISO-8859-9
- 13 = ISO-8859-10
- 17 = Shift-JIS
- 2024 = Windows-31J
- 2026 = Big5
- 38 = euc-kr
- 106 = UTF-8
- 2250 = Windows-1250
- 2251 = Windows-1251
- 2253 = Windows-1253
- 2255 = Windows-1255
- 2256 = Windows-1256
utilizada para o protocolo seguro| | .CORSEnabled : Boolean
CORS (cross-origin resource sharing) status do serviço para o servidor. Por razões de segurança, solicitações de "cross-domain" são proibidas no nível do navegador por padrão. Quando ativado (True), chamadas XHR (por exemplo, Solicitações REST) de páginas da Web fora do domínio podem ser permitidas na sua aplicação (você precisa definir a lista de endereços permitidos na lista de domínio CORS, veja CORSSettings
abaixo). Quando desativado (False, padrão), todas as solicitações de cruzamento de sites enviadas com CORS são ignoradas. Quando habilitado (verdadeiro) e um domínio ou método não permitido envia uma solicitação de site cruzado, ele é rejeitado com uma resposta de erro "403 - proibido".
Padrão: Falso (desabilitado)
Para obter mais informações sobre o CORS, consulte a página de compartilhamento de recursos entre origens na Wikipédia.
| | .CORSSettings : Collection
lista de hosts e métodos permitidos para o serviço CORS | | .debugLog : Number
status do arquivo de log de requisições HTTP| | .defaultHomepage : Text
nome da página inicial padrão| | .HSTSEnabled : Boolean
tempo máximo (em segundos) que HSTS está ativo para cada nova conexão de cliente| | .HTTPCompressionLevel : Number
nivel de compressão para todos os intercambios HTTP comprimidos para o servidor HTTP 4D (petições do cliente ou respostas do servidor)| | .HTTPCompressionThreshold : Number
tamanho limite (bytes) para solicitações abaixo das quais as trocas não devem ser compactadas| | .HTTPEnabled : Boolean
| | .inactiveProcessTimeout : Number
| | .inactiveSessionTimeout : Number
True if legacy sessions are enabled in the web server, False otherwise| | .logRecording : Number
| | .maxConcurrentProcesses : Number
| | .name : Text
| | .perfectForwardSecrecy : Boolean
| | .scalableSession : Boolean
True if scalable sessions are used in the web server, and False otherwise|
| |.sessionCookieSameSite : Text
| |.sessionIPAddressValidation : Boolean
| |
.start() : Object
.start( settings : Object ) : Object
inicia o servidor web sobre o que se aplica| |.stop()
|
WEB Server
Histórico
Versão | Mudanças |
---|---|
v18 R3 | Adicionado |
v19 | suporte para .sessionCookieSameSite |
WEB Server : 4D. WebServer
WEB Server( option : Integer ) : 4D. WebServer
Parameter | Type | Descrição | |
---|---|---|---|
option | Integer | -> | Web server to get (default if omitted = Web server database ) |
Resultado | 4D. WebServer | <- | Web server object |
A função .start()
inicia o servidor web sobre o que se aplica, utilizando as propriedades estabelecidas no parâmetro opcional do objeto settings.
Por padrão, se o parâmetro opção for omitido, o comando retorna uma referência ao servidor Web do banco de dados, i. . o servidor web padrão. Para designar o servidor da Web para retornar, você pode passar uma das seguintes constantes no parâmetro de opção:
Constante | Value | Comentário |
---|---|---|
Web server database | 1 | Current database Web server (default if omitted) |
Web server host database | 2 | Web server of the host database of a component |
Web server receiving request | 3 | Web server that received the request (target Web server) |
O objeto Servidor Web retornado contém os valores atuais das propriedades do Servidor Web.
Exemplo
Do seu componente, você quer saber se o servidor Web do banco de dados host está iniciado:
// Method of a component
var $hostWS : 4D. WebServer
$hostWS:=WEB Server(Web server host database)
If($hostWS.isRunning)
...
End if
WEB Server list
Histórico
Versão | Mudanças |
---|---|
v18 R3 | Adicionado |
WEB Server list : Collection
Parameter | Type | Descrição | |
---|---|---|---|
Resultado | Coleção | <- | Collection of the available Web server objects |
O comando WEB Server list
retorna uma coleção de todos os objetos Web server disponíveis nas aplicações 4D.
Uma aplicação 4D pode conter em qualquer lugar de um a vários servidores Web:
- one Web server for the host database (default Web server)
- one Web server for each component.
Todos os servidores Web disponíveis são retornados pelo comando WEB Server list
, quer estejam realmente executando ou não.
The default Web server object is automatically loaded by 4D at startup. On the other hand, each component Web server that you want to use must be instantiated using the
WEB Server
command.
Você pode usar o . ame propriedade do objeto do servidor Web para identificar o projeto ou componente ao qual cada objeto do servidor Web está anexado na lista.
Exemplo
Queremos saber quantos servidores rodando estão disponíveis:
var $wSList : Collection
var $vRun : Integer
$wSList:=WEB Server list
$vRun:=$wSList.countValues(True;"isRunning")
ALERT(String($vRun)+" web server(s) running on "+String($wSList.length)+" available.")
.accessKeyDefined
.accessKeyDefined : Boolean
A propriedade .accessKeyDefined contémtrue se uma chave de acesso for definida nas configurações do web server. Esta propriedade é usada pelo servidor web WebAdmin para validar a configuração de segurança da interface de administração.
.certificateFolder
.certificateFolder : Text
Rota depasta onde está o certificado de arquivos. O caminho está formatado no caminho completo POSIX usando sistemas de arquivos. Ao usar essa propriedade no parâmetro configurações
do . tart()
função, pode ser um Pasta
objeto.
.characterSet
.characterSet : Number
.characterSet : Text
O conjunto de caracteres que o Servidor Web 4D deve usar para se comunicar com navegadores conectados ao aplicativo. The default value actually depends on the language of the OS. Pode ser um inteiro MIBEnum ou uma string de nome, identificadores definidos por IANA. Aqui está a lista de identificadores correspondentes aos conjuntos de caracteres suportados pelo Servidor Web 4D:
- 4 = ISO-8859-1
- 12 = ISO-8859-9
- 13 = ISO-8859-10
- 17 = Shift-JIS
- 2024 = Windows-31J
- 2026 = Big5
- 38 = euc-kr
- 106 = UTF-8
- 2250 = Windows-1250
- 2251 = Windows-1251
- 2253 = Windows-1253
- 2255 = Windows-1255
- 2256 = Windows-1256
.cipherSuite
.cipherSuite : Text
A lista de cifrado utilizada para o protocolo seguro. Define a prioridade dos algoritmos de criptografia implementados pelo servidor web 4D. Can be a sequence of strings separated by colons (for example "ECDHE-RSA-AES128-..."). See the ciphers page on the OpenSSL site.
.CORSEnabled
.CORSEnabled : Boolean
O CORS (cross-origin resource sharing) status do serviço para o servidor. Por razões de segurança, solicitações de "cross-domain" são proibidas no nível do navegador por padrão. Quando ativado (True), chamadas XHR (por exemplo, Solicitações REST) de páginas da Web fora do domínio podem ser permitidas na sua aplicação (você precisa definir a lista de endereços permitidos na lista de domínio CORS, veja CORSSettings
abaixo). Quando desativado (False, padrão), todas as solicitações de cruzamento de sites enviadas com CORS são ignoradas. Quando habilitado (verdadeiro) e um domínio ou método não permitido envia uma solicitação de site cruzado, ele é rejeitado com uma resposta de erro "403 - proibido".
Padrão: Falso (desabilitado)
Para obter mais informações sobre o CORS, consulte a página de compartilhamento de recursos entre origens na Wikipédia.
.CORSSettings
.CORSSettings : Collection
Uma lista de hosts e métodos permitidos para o serviço CORS (veja CORSenabled
propriedade). Cada objeto deve conter uma propriedade host e, opcionalmente, uma propriedade métodos:
host (text, mandatory): Domain name or IP address from where external pages are allowed to send data requests to the Server via CORS. Multiple domain attributes can be added to create a white list. If host is not present or empty, the object is ignored. Several syntaxes are supported:
- 192.168.5.17:8081
- 192.168.5.17
- 192.168.*
- 192.168.*:8081
- http://192.168.5.17:8081
- http://*.myDomain.com
- http://myProject.myDomain.com
- *.myDomain.com
- myProject.myDomain.com
- *
methods (text, optional): Accepted HTTP method(s) for the corresponding CORS host. Separate each method with a ";" (e,g,: "post;get"). If methods is empty, null, or undefined, all methods are enabled.
.debugLog
.debugLog : Number
O status do arquivo de log de requisições HTTP (HTTPDebugLog_nn. xt, armazenado na pasta "Logs" da aplicação -- nn é o número do arquivo).
- 0 = disabled
- 1 = enabled without body parts (body size is provided in this case)
- 3 = enabled with body parts in response only
- 5 = enabled with body parts in request only
- 7 = enabled with body parts in response and request
.defaultHomepage
.defaultHomepage : Text
O nome da página inicial padrão ou "" para não enviar a página inicial personalizada.
.HSTSEnabled
.HSTSEnabled : Boolean
estado HTTP Strict Transport Security (HSTS). O HSTS permite que o servidor declare que os navegadores só devem interagir com ele através de conexões HTTPS seguras. Navegadores gravarão as informações de HSTS na primeira vez que receberem uma resposta do servidor web, então quaisquer futuras solicitações HTTP serão automaticamente transformadas em solicitações HTTPS. O tempo que essas informações são armazenadas pelo navegador é especificado na propriedade HSTSMaxAge
. A HSTS requer que HTTPS esteja ativado no servidor. HTTP deve também ser habilitado para permitir conexões iniciais de clientes.
.HSTSMaxAge
.HSTSMaxAge : Number
O tempo máximo (em segundos) que HSTS está ativo para cada nova conexão de cliente. Esta informação é armazenada no lado do Cliente durante a duração especificada.
Valor padrão: 63072000 (2 anos).
.HTTPCompressionLevel
.HTTPCompressionLevel : Number
O nivel de compressão para todos os intercambios HTTP comprimidos para o servidor HTTP 4D (petições do cliente ou respostas do servidor). Este seletor permite otimizar trocas priorizando a velocidade de execução (menos compactação) ou a quantidade de compressão (menos velocidade)
Possible values:
- 1 to 9 (where 1 is the fastest compression and 9 the highest).
- -1 = set a compromise between speed and rate of compression.
Padrão = 1 (compressão mais rápida).
.HTTPCompressionThreshold
.HTTPCompressionThreshold : Number
O tamanho limite (bytes) para solicitações abaixo das quais as trocas não devem ser compactadas. Essa configuração é útil para evitar perder o tempo da máquina ao comprimir pequenas trocas.
Limite de compressão padrão = 1024 bytes
.HTTPEnabled
.HTTPEnabled : Boolean
TheHTTP protocol state.
.HTTPPort
.HTTPPort : Number
Thelistening IP port number for HTTP.
Default = 80
.HTTPTrace
.HTTPTrace : Boolean
Theactivation of HTTP TRACE
. For security reasons, by default the Web server rejects HTTP TRACE
requests with an error 405. When enabled, the web server replies to HTTP TRACE
requests with the request line, header, and body.
.HTTPSEnabled
.HTTPSEnabled : Boolean TheHTTPS protocol state.
.HTTPSPort
.HTTPSPort : Number Thelistening IP port number for HTTPS.
Default = 443
.inactiveProcessTimeout
.inactiveProcessTimeout : Number
This property is not returned in scalable sessions mode.
Thelife duration (in minutes) of the inactive legacy session processes. At the end of the timeout, the process is killed on the server, the On Web Legacy Close Session
database method is called, then the legacy session context is destroyed.
Default = 480 minutes
.inactiveSessionTimeout
.inactiveSessionTimeout : Number
This property is not returned in scalable sessions mode.
Thelife duration (in minutes) of inactive legacy sessions (duration set in cookie). At the end of this period, the session cookie expires and is no longer sent by the HTTP client.
Default = 480 minutes
.IPAddressToListen
.IPAddressToListen : Text
TheIP address on which the 4D Web Server will receive HTTP requests. By default, no specific address is defined. Both IPv6 string formats and IPv4 string formats are supported.
.isRunning
.isRunning : Boolean
Read-only property
Theweb server running state.
.keepSession
.keepSession : Boolean
True if legacy sessions are enabled in the web server, False otherwise.
See also:
.logRecording
.logRecording : Number
Thelog requests (logweb.txt) recording value.
- 0 = Do not record (default)
- 1 = Record in CLF format
- 2 = Record in DLF format
- 3 = Record in ELF format
- 4 = Record in WLF format
.maxConcurrentProcesses
.maxConcurrentProcesses : Number
Themaximum number of concurrent web processes supported by the web server. When this number (minus one) is reached, 4D will not create any other processes and returns the HTTP status 503 - Service Unavailable to all new requests.
Possible values: 10 - 32000
Default = 100
.maxRequestSize
.maxRequestSize : Number
Themaximum size (in bytes) of incoming HTTP requests (POST) that the web server is allowed to process. Passing the maximum value (2147483647) means that, in practice, no limit is set. This limit is used to avoid web server saturation due to incoming requests that are too large. If a request reaches this limit, the web server rejects it.
Possible values: 500000 - 2147483647
.maxSessions
.maxSessions : Number
This property is not returned in scalable sessions mode.
Themaximum number of simultaneous legacy sessions. When you reach the limit, the oldest legacy session is closed (and On Web Legacy Close Session
database method is called) if the web server needs to create a new one. The number of simultaneous legacy sessions cannot exceed the total number of web processes (maxConcurrentProcesses
property, 100 by default)
.minTLSVersion
.minTLSVersion : Number
Theminimum TLS version accepted for connections. Connection attempts from clients supporting only versions below the minimum will be rejected.
Possible values:
- 1 = TLSv1_0
- 2 = TLSv1_1
- 3 = TLSv1_2 (default)
- 4 = TLSv1_3
If modified, the server must be restarted to use the new value.
.name
.name : Text
Read-only property
Thename of the web server application.
.openSSLVersion
.openSSLVersion : Text
Read-only property
Theversion of the OpenSSL library used.
.perfectForwardSecrecy
.perfectForwardSecrecy : Boolean
Read-only property
ThePFS availability on the server.
.rootFolder
.rootFolder : Text
Thepath of web server root folder. O caminho está formatado no caminho completo POSIX usando sistemas de arquivos. When using this property in the settings
parameter, it can be a Folder
object.
.scalableSession
.scalableSession : Boolean
True if scalable sessions are used in the web server, and False otherwise.
See also:
.sessionCookieDomain
.sessionCookieDomain : Text
The"domain" field of the session cookie. Used to control the scope of the session cookies. If you set, for example, the value "/*.4d.fr" for this selector, the client will only send a cookie when the request is addressed to the domain ".4d.fr", which excludes servers hosting external static data.
.sessionCookieName
.sessionCookieName : Text
Thename of the cookie used for storing the session ID.
Read-only property
.sessionCookiePath
.sessionCookiePath : Text
The"path" field of the session cookie. Used to control the scope of the session cookies. If you set, for example, the value "/4DACTION" for this selector, the client will only send a cookie for dynamic requests beginning with 4DACTION, and not for pictures, static pages, etc.
.sessionCookieSameSite
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.sessionCookieSameSite : Text
The"SameSite" session cookie value. Possible values (using constants):
Constante | Value | Descrição |
---|---|---|
Web SameSite Strict | "Strict" | Default value - Cookies are only sent in a first-party context |
Web SameSite Lax | "Lax" | Cookies are also sent on cross-site subrequests but only when a user is navigating to the origin site (i.e. when following a link). |
Web SameSite None | "None" | Cookies are sent in all contexts, i.e in responses to both first-party and cross-origin requests. |
See the Session Cookie SameSite description for detailed information.
.sessionIPAddressValidation
.sessionIPAddressValidation : Boolean
This property is not used in scalable sessions mode (there is no IP address validation).
TheIP address validation for session cookies. For security reasons, by default the web server checks the IP address of each request containing a session cookie and rejects it if this address does not match the IP address used to create the cookie. In some specific applications, you may want to disable this validation and accept session cookies, even when their IP addresses do not match. For example when mobile devices switch between WiFi and 3G/4G networks, their IP address will change. In this case, you can allow clients to be able to continue using their web sessions even when the IP addresses change (this setting lowers the security level of your application).
.start()
Histórico
Versão | Mudanças |
---|---|
v18 R3 | Adicionado |
.start() : Object
.start( settings : Object ) : Object
Parameter | Type | Descrição | |
---|---|---|---|
settings | Objeto | -> | Web server settings to set at startup |
Resultado | Objeto | <- | Status of the web server startup |
The .start()
functionstarts the web server on which it is applied, using properties set in the optional settings object parameter.
The web server starts with default settings defined in the settings file of the project or (host database only) using the WEB SET OPTION
command. However, using the settings parameter, you can define customized properties for the web server session.
All settings of Web Server objects can be customized, except read-only properties (.isRunning, .name, .openSSLVersion, .perfectForwardSecrecy, and [.sessionCookieName(#sessioncookiename)]).
Customized session settings will be reset when the .stop()
function is called.
Returned object
The function returns an object describing the Web server launch status. This object can contain the following properties:
Propriedade | Type | Descrição | |
---|---|---|---|
success | Booleano | True if the web server was correctly started, False otherwise | |
errors | Coleção | 4D error stack (not returned if the web server started successfully) | |
[].errCode | Número | 4D error code | |
[].message | Texto | Description of the 4D error | |
[].componentSignature | Texto | Signature of the internal component which returned the error |
If the Web server was already launched, an error is returned.
Exemplo
var $settings;$result : Object
var $webServer : 4D. WebServer
$settings:=New object("HTTPPort";8080;"defaultHomepage";"myAdminHomepage.html")
$webServer:=WEB Server
$result:=$webServer.start($settings)
If($result.success)
//...
End if
.stop()
Histórico
Versão | Mudanças |
---|---|
v18 R3 | Adicionado |
.stop()
| Parameter | Type | | Descrição | | --------- | ---- | | ------------------------------- | | | | | Does not require any parameters |
The .stop()
functionstops the web server on which it is applied.
If the web server was started, all web connections and web processes are closed, once the currently handled requests are finished. If the web server was not started, the method does nothing.
This function resets the customized web settings defined for the session using the settings parameter of the
.start()
function, if any.
Exemplo
To stop the database Web server:
var $webServer : 4D. WebServer
$webServer:=WEB Server(Web server database)
$webServer.stop()