Saltar para o conteúdo principal
Versão: 20 R5 BETA

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.

Objeto Web Server

Web server objects are instantiated with the WEB Server command.

Eles oferecem as propriedades abaixo e funções:

Resumo

.accessKeyDefined : Boolean
true if an access key is defined in the settings of the web server
.certificateFolder : Text
folder where the certificate files are located
.characterSet : Number
.characterSet : Text

character set that the 4D Web Server should use to communicate with browsers connecting to the application
.cipherSuite : Text
cipher list used for the secure protocol
.CORSEnabled : Boolean
CORS (Cross-origin resource sharing) service status for the web server
.CORSSettings : Collection
list of allowed hosts and methods for the CORS service
.debugLog : Number
status of the HTTP request log file
.defaultHomepage : Text
name of the default home page
.HSTSEnabled : Boolean
HTTP Strict Transport Security (HSTS) status
.HSTSMaxAge : Number
maximum length of time (in seconds) that HSTS is active for each new client connection
.HTTPCompressionLevel : Number
compression level for all compressed HTTP exchanges for the 4D HTTP server (client requests or server replies)
.HTTPCompressionThreshold : Number
size threshold (bytes) for requests below which exchanges should not be compressed
.HTTPEnabled : Boolean
HTTP protocol state
.HTTPPort : Number
listening IP port number for HTTP
.HTTPTrace : Boolean
activation of HTTP TRACE
.HTTPSEnabled : Boolean
HTTPS protocol state
.HTTPSPort : Number
listening IP port number for HTTPS
.inactiveProcessTimeout : Number
life duration (in minutes) of the inactive legacy session processes
.inactiveSessionTimeout : Number
life duration (in minutes) of inactive legacy sessions (duration set in cookie)
.IPAddressToListen : Text
IP address on which the 4D Web Server will receive HTTP requests
.isRunning : Boolean
web server running state
.keepSession : Boolean
True if legacy sessions are enabled in the web server, False otherwise
.logRecording : Number
log requests (logweb.txt) recording value
.maxConcurrentProcesses : Number
maximum number of concurrent web processes supported by the web server
.maxRequestSize : Number
maximum size (in bytes) of incoming HTTP requests (POST) that the web server is allowed to process
.maxSessions : Number
maximum number of simultaneous legacy sessions
.minTLSVersion : Number
minimum TLS version accepted for connections
.name : Text
name of the web server application
.openSSLVersion : Text
version of the OpenSSL library used
.perfectForwardSecrecy : Boolean
PFS availability on the server
.rootFolder : Text
path of web server root folder
.scalableSession : Boolean
True if scalable sessions are used in the web server, and False otherwise
.sessionCookieDomain : Text
"domain" field of the session cookie
.sessionCookieName : Text
name of the cookie used for storing the session ID
.sessionCookiePath : Text
"path" field of the session cookie
.sessionCookieSameSite : Text
"SameSite" session cookie value
.sessionIPAddressValidation : Boolean
IP address validation for session cookies

| .start() : Object
.start( settings : Object ) : Object

starts the web server on which it is applied | | .stop()
stops the web server on which it is applied |

WEB Server

História
ReleaseMudanças
18 R3Adicionado
19suporte para .sessionCookieSameSite

WEB Server : 4D.WebServer
WEB Server( option : Integer ) : 4D.WebServer

ParâmetroTipoDescrição
optionInteger->Web server to get (default if omitted = Web server database)
Resultados4D. WebServer<-Objeto Web Server

The WEB Server command returns the default Web server object, or the Web server object defined through the option parameter.

By default, if the option parameter is omitted, the command returns a reference to the Web server of the database, i.e. the default Web server. To designate the Web server to return, you can pass one of the following constants in the option parameter:

ParâmetrosValorComentário
Web server database1Servidor Web de banco de dados atual (padrão caso omitido)
<a href="#keepsession">.keepSession</a>2Servidor Web do banco de dados de host de um componente
Solicitação de recebimento do servidor web3Servidor web que recebeu o pedido (servidor Web de destino)

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ória
ReleaseMudanças
18 R3Adicionado

WEB Server list : Collection

ParâmetroTipoDescrição
ResultadosCollection<-Coleção de objetos do Servidor Web disponível

The WEB Server list command returns a collection of all Web server objects available in the 4D application.

Uma aplicação 4D pode conter em qualquer lugar de um a vários servidores Web:

  • um servidor Web para o banco de dados host (servidor Web padrão)
  • um servidor web para cada componente.

All available Web servers are returned by the WEB Server list command, whether they are actually running or not.

O objeto do servidor Web padrão é carregado automaticamente pelo 4D na inicialização. On the other hand, each component Web server that you want to use must be instantiated using the WEB Server command.

You can use the .name property of the Web server object to identify the project or component to which each Web server object in the list is attached.

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

The .accessKeyDefined property contains true if an access key is defined in the settings of the 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

Path of the folder where the certificate files are located. O caminho está formatado no caminho completo POSIX usando sistemas de arquivos. When using this property in the settings parameter of the .start() function, it can be a Folder object.

.characterSet

.characterSet : Number
.characterSet : Text

The character set that the 4D Web Server should use to communicate with browsers connecting to the application. O valor padrão realmente depende da linguagem do SO. Can be a MIBEnum integer or a Name string, identifiers defined by 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

The cipher list used for the secure protocol. Define a prioridade dos algoritmos de criptografia implementados pelo servidor web 4D. Pode ser uma sequência de frases separadas por dois pontos (por exemplo, "ECDHE-RSA-AES128-..."). See the ciphers page on the OpenSSL site.

.CORSEnabled

.CORSEnabled : Boolean

The CORS (Cross-origin resource sharing) service status for the web server. Por razões de segurança, solicitações de "cross-domain" são proibidas no nível do navegador por padrão. When enabled (True), XHR calls (e.g. REST requests) from Web pages outside the domain can be allowed in your application (you need to define the list of allowed addresses in the CORS domain list, see CORSSettings below). 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)

For more information about CORS, please refer to the Cross-origin resource sharing page on Wikipedia.

.CORSSettings

.CORSSettings : Collection

Contains the list of allowed hosts and methods for the CORS service (see CORSEnabled property). Each object must contain a host property and, optionally, a methods property:

  • host (text, mandatory): Domain name or IP address from where external pages are allowed to send data requests to the Server via CORS. Vários atributos de domínio podem ser adicionados para criar uma lista branca. If host is not present or empty, the object is ignored. Várias sintaxes são suportadas:

  • methods (text, optional): Accepted HTTP method(s) for the corresponding CORS host. Separar cada método com um ";" (por exemplo: "post;get"). If methods is empty, null, or undefined, all methods are enabled.

.debugLog

.debugLog : Number

The status of the HTTP request log file (HTTPDebugLog_nn.txt, stored in the "Logs" folder of the application -- nn is the file number).

  • 0 = desactivado
  • 1 = habilitado sem partes do corpo (o tamanho do corpo é fornecido neste caso)
  • 3 = ativado com partes do corpo apenas em resposta
  • 5 = ativado com partes do corpo apenas em resposta
  • 7 = ativado com partes do corpo apenas em resposta

.defaultHomepage

.defaultHomepage : Text

The name of the default home page or "" to not send the custom home page.

.HSTSEnabled

.HSTSEnabled : Boolean

The HTTP Strict Transport Security (HSTS) status. 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. The length of time this information is stored by the browser is specified with the HSTSMaxAge property. 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

The maximum length of time (in seconds) that HSTS is active for each new client connection. Esta informação é armazenada no lado do Cliente durante a duração especificada.

Valor padrão: 63072000 (2 anos).

.HTTPCompressionLevel

.HTTPCompressionLevel : Number

The compression level for all compressed HTTP exchanges for the 4D HTTP server (client requests or server replies). Este seletor permite otimizar trocas priorizando a velocidade de execução (menos compactação) ou a quantidade de compressão (menos velocidade)

Valores possíveis:

  • 1 a 9 (onde 1 é a compressão mais rápida e 9 a mais alta).
  • -1 = define um compromisso entre a velocidade e a taxa de compressão.

Padrão = 1 (compressão mais rápida).

.HTTPCompressionThreshold

.HTTPCompressionThreshold : Number

The size threshold (bytes) for requests below which exchanges should not be compressed. 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

The HTTP protocol state.

.HTTPPort

.HTTPPort : Number

The listening IP port number for HTTP.

O padrão = 80

.HTTPTrace

.HTTPTrace : Boolean

The activation 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

The HTTPS protocol state.

.HTTPSPort

.HTTPSPort : Number

The listening IP port number for HTTPS.

O padrão = 443

.inactiveProcessTimeout

.inactiveProcessTimeout : Number

This property is not returned in scalable sessions mode.

The life 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 minutos

.inactiveSessionTimeout

.inactiveSessionTimeout : Number

This property is not returned in scalable sessions mode.

The life duration (in minutes) of inactive legacy sessions (duration set in cookie). No final do período, o cookie da sessão expira e não é mais enviada pelo cliente HTTP.

Default = 480 minutos

.IPAddressToListen

.IPAddressToListen : Text

The IP address on which the 4D Web Server will receive HTTP requests. Normalmente, nenhum endereço específico é definido. Os formatos string IPv6 e IPv4 são compatíveis

.isRunning

.isRunning : Boolean

Propriedade apenas leitura

The web server running state.

.keepSession

.keepSession : Boolean

Contains True if legacy sessions are enabled in the web server, False otherwise.

Veja também

.scalableSession

.logRecording

.logRecording : Number

The log requests (logweb.txt) recording value.

  • 0 = Não registrar (padrão)
  • 1 = Guardar no formato CLF
  • 2 = Guardar no formato DLF
  • 3 = Guardar no formato ELF
  • 4 = Guardar no formato WLF

.maxConcurrentProcesses

.maxConcurrentProcesses : Number

The maximum number of concurrent web processes supported by the web server. Quando este número (menos um) é alcançado, 4D não cria outro processos e retorna o status HTTP 503 - Serviço indisponível para novas petições.

Valores possíveis: 10 - 32000

Normal = 100

.maxRequestSize

.maxRequestSize : Number

Contains the maximum size (in bytes) of incoming HTTP requests (POST) that the web server is allowed to process. Passar o valor máximo (2147483647) significa na prática que não é estabelecido um limite. Este limite é utilizado para evitar a saturação do servidor web devido a pedidos recebidos demasiado grandes. Se um pedido atingir este limite, o servidor web rejeita-o.

Valores possíveis: 500000 - 2147483647

.maxSessions

.maxSessions : Number

This property is not returned in scalable sessions mode.

Contains the maximum 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

The minimum TLS version accepted for connections. As tentativas de ligação de clientes que suportam apenas versões abaixo do mínimo serão rejeitadas.

Valores possíveis:

  • 1 = TLSv1_0
  • 2 = TLSv1_1
  • 3 = TLSv1_2 (padrão)
  • 4 = TLSv1_3

Se modificado, o servidor deve ser reiniciado para utilizar o novo valor.

.name

.name : Text

Propriedade apenas leitura

The name of the web server application.

.openSSLVersion

.openSSLVersion : Text

Propriedade apenas leitura

The version of the OpenSSL library used.

.perfectForwardSecrecy

.perfectForwardSecrecy : Boolean

Propriedade apenas leitura

The PFS availability on the server.

.rootFolder

.rootFolder : Text

The path 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

Contains True if scalable sessions are used in the web server, and False otherwise.

Veja também

.keepSession

.sessionCookieDomain

.sessionCookieDomain : Text

The "domain" field of the session cookie. Utilizado para controlar o alcance dos cookies da sessão. Se definir, por exemplo, o valor "/*.4d.fr" para este selector, o cliente só enviará um cookie quando o pedido for dirigido ao domínio ".4d.fr", o que exclui os servidores que hospedam dados estáticos externos.

.sessionCookieName

.sessionCookieName : Text

The name of the cookie used for storing the session ID.

Propriedade apenas leitura

.sessionCookiePath

.sessionCookiePath : Text

The "path" field of the session cookie. Utilizado para controlar o alcance dos cookies da sessão. Se definir, por exemplo, o valor "/4DACTION" para este selector, o cliente só enviará um cookie para pedidos dinâmicos que comecem por 4DACTION, e não para imagens, páginas estáticas, etc.

.sessionCookieSameSite

História
ReleaseMudanças
19Adicionado

.sessionCookieSameSite : Text

The "SameSite" session cookie value. Possíveis valores (usando constantes):

ParâmetrosValorDescrição
Web SameSite Strict"Strict"Default value - Cookies are only sent in a first-party context
Web SameSite Lax"Lax"Os cookies também são enviados em pedidos cruzados mas apenas quando um utilizador está a navegar para o sítio de origem (isto é, quando segue um link).
Web SameSite None"None"Os cookies são enviados em todos os contextos, ou seja, em resposta a pedidos tanto de primeira parte como de origem cruzada.

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).

The IP address validation for session cookies. Por razões de segurança, por defeito o servidor web verifica o endereço IP de cada pedido contendo um cookie de sessão e rejeita-o se este endereço não corresponder ao endereço IP utilizado para criar o cookie. Em algumas aplicações específicas, poderá querer desactivar esta validação e aceitar cookies de sessão, mesmo quando os seus endereços IP não correspondem. Por exemplo, quando os dispositivos móveis mudam entre redes WiFi e 3G/4G, o seu endereço IP muda. Neste caso, pode permitir que os clientes possam continuar a utilizar as suas sessões web mesmo quando os endereços IP mudam (esta configuração reduz o nível de segurança da sua aplicação).

.start()

História
ReleaseMudanças
18 R3Adicionado

.start() : Object
.start( settings : Object ) : Object

ParâmetroTipoDescrição
settingsObject->Configurações do servidor Web a definir no arranque
ResultadosObject<-Estado de arranque do servidor web

The .start() function starts 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.

Objeto devolvido

A função devolve um objecto que descreve o estado de lançamento do servidor Web. Este objeto pode conter as seguintes propriedades:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se o servidor web foi correctamente iniciado, Falso caso contrário
errorsCollectionpilha de erros 4D (não devolvidos se o servidor web começou com sucesso)
[].errCodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura da componente interna que devolveu o erro

Se o servidor Web já tiver sido lançado, é devolvido um erro.

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ória
ReleaseMudanças
18 R3Adicionado

.stop()

ParâmetroTipoDescrição
Não exige nenhum parâmetro

The .stop() function stops the web server on which it is applied.

Se o servidor web foi iniciado, todas as ligações e processos web são fechados, uma vez terminados os pedidos actualmente tratados. Se o servidor web não foi iniciado, o método não faz nada.

This function resets the customized web settings defined for the session using the settings parameter of the .start() function, if any.

Exemplo

Para parar o servidor Web da base de dados:

 var $webServer : 4D. WebServer

$webServer:=WEB Server(Web server database)
$webServer.stop()