The embedded server
spring_boot_starter_web runs an HTTP server inside the application. It starts when the context is ready and stops when the context closes. You configure it with server.* properties.
Why
You do not write HttpServer.bind or a request loop. The starter does it for you, in the same way as Spring Boot runs Tomcat for you:
- the
webServerFactorybean creates the server from theserver.*properties; - the
webServerStartStopLifecyclebean starts it after the beans are ready and stops it at shutdown; - every request goes to the
dispatcherHandlerbean, which runs the filters and the controllers.
The default server is dart:io's HttpServer. It runs on the Dart VM, in a compiled executable, and in a Flutter app on Android, iOS, macOS, Windows and Linux. It speaks HTTP/1.1 (with TLS if you want). It does not speak HTTP/2.
Example
# lib/resources/application.yml
server:
port: 8080
address: 0.0.0.0
context-path: /shop
max-http-request-body-size: 20MB
mime-mappings:
wasm: application/wasm
spring:
main:
register-shutdown-hook: true # Ctrl+C and SIGTERM stop the server gracefully
mvc:
log-request-details: false
// bin/main.dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
import 'spring_gen/main.spring.dart';
@SpringBootApplication()
void main(List<String> args) => runApplication(args);
dart run build_runner build
dart run bin/main.dart
# INFO Web server started on port 8080 (http)
With this configuration, @GetMapping('/books') answers GET http://host:8080/shop/books.
Properties
| Key | Type | Default | Meaning |
|---|---|---|---|
server.port |
int |
8080 |
The port to listen on. 0 picks a free port. |
server.address |
String |
all interfaces; 127.0.0.1 in Flutter apps |
The address to listen on: an IP address or a host name. |
server.context-path |
String |
none | A prefix of every path, such as /shop. |
server.max-http-request-body-size |
DataSize |
10MB |
The largest request body. Larger is a 413. -1: no limit. |
server.mime-mappings.<ext> |
Map<String, String> |
empty | More media types for static files, by file extension. |
spring.main.web-application-type |
String |
not set | none starts no server. |
spring.test.web-environment |
String |
not set | Set by tests: which test environments start a server. |
spring.mvc.log-request-details |
bool |
false |
Show parameter and header values in the request logs. |
local.server.port |
int |
written by the server | The port the server really listens on. Read it; do not set it. |
The other server.* keys have their own pages: TLS, compression, timeouts, overload, the pool of isolates and its scaling, reverse proxy, shutdown, WebSocket and sessions. The full list is on All properties.
server.port
- Type:
int. Default:8080. - What it does: the TCP port the server listens on.
0: the system picks a free port. The real port is known only once the server listens. Read it fromlocal.server.port, from aWebServerInitializedEvent, or fromWebServer.port.- Why change it: another program uses
8080; a platform gives you a port (aPORTvariable); several instances run on one machine; tests need a free port. - Example:
server.port=9090, or--server.port=9090on the command line, orSERVER_PORT=9090in the environment. - Wrong value:
server.port=abcstops the start with a binding failure that namesserver.port. - Port in use: the start fails. No
ApplicationStartedEvent, no runners, noApplicationReadyEvent. TheApplicationFailedEventis published, the context closes, and the program ends with a non-zero exit code. The report:
Web server failed to start. Port 8080 was already in use.
Action: Identify and stop the process that is listening on port 8080, or
configure this application to listen on another port (server.port; 0 picks a free one).
The port is in use also when the same process already listens on it.
A port computed in code goes through a WebServerFactoryCustomizer (see "Changing the server in code" below).
local.server.port
- Type:
int. Set by: the server, once it listens. - What it is: the port the server really got. With
server.port=0it is the only way to know the port from configuration. - Where it lives: a property source named
server.ports, put first in the environment. - Why you read it: to log a URL, to register the service with a discovery server, or to call the server in a test.
@Component()
@Log()
class StartupUrl {
@EventListener()
void onServer(WebServerInitializedEvent event) =>
log.info('Open http://localhost:${event.port}/');
}
Setting local.server.port yourself does nothing: nothing reads it to choose the port.
server.address
- Type:
String. Default: not set, which listens on every interface (IPv4 and IPv6). In a Flutter app the default is127.0.0.1. - Values: an IPv4 or IPv6 address (
0.0.0.0,127.0.0.1,::1),localhost(read as127.0.0.1), or a host name, which is looked up when the server starts (the first address found is used). - Why change it: listen on
127.0.0.1only, so that the server is reachable from this machine only (a local tool, a server behind a proxy on the same host). Or, in a Flutter app, set0.0.0.0on purpose to open the server to the local network. - Example:
server.address=127.0.0.1. - Wrong value: an address that cannot be bound, or a host name that cannot be looked up, fails the start with
WebServerException: cannot listen on <address>:<port>and the socket error.
server.context-path
- Type:
String. Default: none. - What it does: every request path must start with this prefix. The prefix is removed before routing. So
@GetMapping('/books')answers/shop/books, and/shopalone is the path/. - Outside the prefix: a request to
/books(without/shop) gets a 404, as for a path that no handler takes. - Normalised: a missing leading
/is added and trailing/are removed.shop/becomes/shop. - Also affects: the default
Pathof the session cookie (server.session.cookie.path), so the cookie goes only to the application's paths. - Why change it: several applications share one host behind a proxy (
/shop,/admin), and the proxy passes the full path. - Example:
server.context-path=/shop. - Note: it is read by the dispatcher directly. A
WebServerFactoryCustomizerthat changescontextPathin the factory's settings does not change routing.
server.max-http-request-body-size
- Type:
DataSize(512KB,10MB,1GB; a plain number is bytes). Default:10MB.-1: no limit. - What it does: a request body larger than this is answered with
413 Payload Too Large, whatever itsContent-Type. WhenContent-Lengthalready says it is too large, the 413 comes before anything is read. A chunked body is counted while it is read. - Uploads: the multipart resolver reads
multipart/form-datawith its own limit,spring.web.multipart.max-request-size, instead of this one. See Uploads. - One request: a handler can set its own limit for the request it handles, before it reads the body, through the request attribute
maxRequestBodySizeAttribute:
import 'dart:io' show File;
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
@RestController()
class ImageController {
// Disk images up to 4 GB, written to a file as they arrive.
@PutMapping('/images/{name}')
@ResponseStatus(HttpStatus.noContent)
Future<void> upload(ServerHttpRequest request, @PathVariable() String name) async {
request.attributes[maxRequestBodySizeAttribute] = 4 << 30;
await request.body.pipe(File('/srv/images/$name').openWrite());
}
}
- Why change it: raise it for an API that takes big JSON documents; lower it to protect a small service from large bodies.
- Not in Spring Boot: Tomcat has no limit of this kind for every body. This is the starter's own key.
server.mime-mappings.*
- Type: a map from file extension to media type. Default: empty (the built-in types apply).
- What it does: gives the
Content-Typeof static files by extension, on top of the built-in table. An extension listed here wins over the built-in type. The extension is matched in any case (WASMandwasmare the same). - Why change it: a file type the built-in table does not know, or a type you want to send differently.
- Example:
server:
mime-mappings:
wasm: application/wasm
webmanifest: application/manifest+json
server.mime-mappings.wasm=application/wasm
server.mime-mappings.webmanifest=application/manifest+json
A file whose type is unknown is sent as application/octet-stream. See Static resources.
spring.main.web-application-type
- Type:
String. Default: not set: a server starts. none: the web beans exist (the dispatcher, the controllers,MockMvcin tests), but no server starts. The value is compared without case.- Any other value: the server starts. There is no
servletorreactivechoice: there is one kind of server. - Why change it: run a command-line task of the same application (a migration, a report) without opening a port. Or build for the browser, where no server can start.
- Example:
dart run bin/main.dart --spring.main.web-application-type=none.
spring.test.web-environment
- Type:
String. Default: not set: a server starts. - Values:
mock,random-port,defined-port,none. - Who sets it: the test support.
springBootTest(springApplication, webEnvironment: ...)sets it (mockby default), andApplicationContextRunnersetsmock. You do not set it inapplication.yml. - What each value does:
| Value | Server | Port |
|---|---|---|
mock |
none; MockMvc calls the dispatcher in memory |
— |
random-port |
a real server | 0, a free port, whatever server.port says |
defined-port |
a real server | server.port |
none |
none | — |
Any other value starts no server either. See Testing.
spring.mvc.log-request-details
- Type:
bool. Default:false. - What it does: the dispatcher logs every request at
debuglevel, under the loggerspring.web.servlet.DispatcherServlet. By default the values of query parameters and headers are shown asmasked, because they may hold secrets. Withtruethey are shown. - Always masked: credentials stay
maskedeven withtrue: the headersAuthorization,Proxy-Authorization,Cookie,Set-Cookie, and any header or parameter whose name containstoken,secret,key,passwordorsession. - Headers: shown only at
tracelevel. - Why change it: debugging, on a developer machine. Leave it
falsein production.
logging.level.spring.web.servlet.DispatcherServlet=trace
spring.mvc.log-request-details=true
DEBUG GET "/api/books", parameters={q=[dune], page=[2]}, headers={host: localhost:8080, authorization: masked}
DEBUG Completed 200 OK
Without log-request-details, the same request logs parameters={masked} and headers={masked}.
The startup log line
When the server listens, the starter logs at info level, under the logger spring.web.server:
Web server started on port 8080 (http)
The port is the real one (useful with server.port=0). The scheme is https when server.ssl.certificate is set and server.ssl.enabled is not false. When the server stops, it logs Web server stopped.
Other loggers of the starter:
| Logger | What |
|---|---|
spring.web.server |
start, stop, graceful shutdown, server errors, WebSocket sessions dropped |
spring.web.servlet.DispatcherServlet |
one line per request and its result (debug) |
spring.web.mvc |
the mappings found at startup (debug: their count; trace: each one), errors written |
spring.web.forwarded |
forwarded headers applied or ignored (debug) |
spring.web.session |
sessions |
spring.web.multipart |
uploads |
The server's lifecycle
- The context starts. The
webServerStartStopLifecyclebean is aSmartLifecyclewith phaseSmartLifecycle.defaultPhase - 2048, as in Spring Boot. It starts before the lifecycle beans of the default phase and stops after them. - Should a server run? Not when
spring.main.web-application-type=none. In a test, only forrandom-portanddefined-port. - The server is created. The
webServerFactorybean is asked for a server, with thedispatcherHandleras its handler. - The socket is bound.
dart:iobinds asynchronously.SpringApplicationwaits for it before it publishesApplicationStartedEvent, runs the runners and publishesApplicationReadyEvent. So when yourApplicationRunnerruns, the server already listens. - The port is published.
local.server.portis set, the startup line is logged, and aWebServerInitializedEventis published. - The context closes. The server stops as
server.shutdownsays. See Shutdown.
To wait for the server in code (for example in a test without the test starter):
final lifecycle = context.getBean<WebServerStartStopLifecycle>();
final server = await lifecycle.started; // null when no server runs
final uri = Uri.parse('http://localhost:${server!.port}/api/books');
A failure to start other than a port in use (an address that cannot be bound, a certificate that cannot be read) also fails the start. In a context started without SpringApplication, the failure is logged as Web server failed to start and the context closes.
Stopping with Ctrl+C
spring.main.register-shutdown-hook is false by default here (Spring Boot: true), because listening for signals keeps a Dart program alive. Set it to true so that Ctrl+C (SIGINT) and SIGTERM close the context. Then the server stops gracefully and @PreDestroy methods run. Without it, the signal ends the process at once.
What the server answers by itself
Some requests never reach your filters or controllers. The server answers them with a ProblemDetail (application/problem+json):
| Request | Answer |
|---|---|
| A method the starter does not know | 501 Not Implemented |
With server.ssl.client-auth=need, no client certificate |
403 Forbidden |
HTTP/1.1 without Host, a malformed Host, or an absolute target whose host is not the Host header |
400 Bad Request |
An encoded /, \ or NUL in the path (%2F, %5C, %00) |
400 |
A . or .. segment hidden behind ; (/files/..;x/secret) |
400 |
A % escape that is not valid UTF-8 in the path or query (/%FF) |
400 |
Other rules of the dart:io server:
- No
Serverheader and noX-XSS-Protection.dart:io'sX-Frame-Options: SAMEORIGINandX-Content-Type-Options: nosniffare sent. - No default
Content-Type. An answer whose media type the application did not set has none. - 1xx, 204, 304 get no
Content-Lengthand noTransfer-Encoding; a 304 noContent-Type. A body written to them is dropped. AHEADkeeps the headers of theGET. - An unread body (an upload answered with a 413 or 415): the answer goes out first, then up to 2 MB of the body are read and dropped, for at most 5 seconds, so the connection can serve the next request. A longer or slower body closes the connection.
- An error after the response was committed: the connection is dropped without finishing the response (no final chunk). The client sees a broken response, not a short one that looks complete.
- A response header
dart:iocannot send (a non-ASCII character, a line break) fails before anything is sent: the header is dropped and the error is answered with a 500. - No connection limit (Tomcat's
max-connections). Put a proxy in front, or rely on the system's limit of open files.
Known limits of dart:io that matter behind a proxy:
- Two
Hostheaders: the last one is used (Tomcat answers 400). - A
%without two hex digits is read as a plain%(/a%G1is/a%25G1). - A raw
\in the target becomes/, and..segments are then resolved:/files/..\..\secretarrives as/secret. A proxy whose rules look at paths must refuse\itself. - A request with both
Content-LengthandTransfer-Encodingis answered 400, and its connection closes, when the server sees both headers.dart:ioshows both only in some spellings (the length first and the encoding not written exactlychunked); in the others it drops theContent-Lengthand the request is read as chunked. Use a proxy that refuses such requests, to prevent request smuggling.
Changing the server in code
Properties cover most needs. When a value is computed, declare a WebServerFactoryCustomizer bean. The starter calls each one once, on the default factory, after it applied server.*:
import 'dart:io' show Platform;
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
// The hosting platform gives the port in the PORT variable.
@Component()
class PortCustomizer implements WebServerFactoryCustomizer {
@override
void customize(ConfigurableWebServerFactory factory) =>
factory.settings = factory.settings.copyWith(
port: int.parse(Platform.environment['PORT'] ?? '8080'),
);
}
ServerProperties.copyWith keeps a value when its argument is null, so it cannot reset address, ssl or a timeout to "none". server.context-path and server.request-timeout are read by the dispatcher from the properties, so a customizer cannot change them.
To replace the server entirely, declare your own WebServerFactory bean. The default one backs off (@ConditionalOnMissingBean):
@Configuration()
class ServerConfig {
@Bean()
WebServerFactory webServerFactory() => MyServerFactory(); // returns a WebServer
}
A WebServer has start(), stop({Duration? timeout}) and port. Everything above the server works on ServerHttpRequest and ServerHttpResponse and never imports dart:io, so another server needs only these two classes. IoWebServerFactory and IoWebServer are in package:spring_boot_starter_web/io.dart, which you can import to wrap the default server or to start one outside the context:
import 'package:spring_boot_starter_web/io.dart';
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
Future<void> main() async {
final server = IoWebServerFactory(const ServerProperties(port: 0)).getWebServer(
FunctionHttpHandler((request, response) => response.send(200, 'pong')),
);
await server.start();
print('listening on ${server.port}');
}
Running in Flutter
The starter works in a Flutter app on Android, iOS, macOS, Windows and Linux. The server runs in the main isolate, with the same beans as the widgets: a local API, a companion server for other devices, a page served to a browser on the same machine.
127.0.0.1by default. An app opens no port to the network unlessserver.addresssays so (server.address=0.0.0.0).- Do not block the UI.
HttpServer's I/O is asynchronous, but heavy synchronous work in a handler blocks the UI too. Move it into another isolate with the task executor. - One isolate.
server.isolates.*is ignored in a Flutter app, with a warning. See A pool of isolates. - In the background the context pauses: the server stops and frees the port. It starts again when the app comes back.
spring.flutter.lifecycle.pause-in-background=falsekeeps it running. - Platform permissions:
- macOS: the
com.apple.security.network.serverentitlement; - Android: the
INTERNETpermission in the release manifest; - iOS: binding beyond localhost asks the user for local network access (
NSLocalNetworkUsageDescriptioninInfo.plist).
- macOS: the
- The web has no server sockets, and the starter's module is
nativeonly: in a browser build the generated application does not list it, so the app starts without a server and carries none of the starter's code (see Modules of one platform). A context that names the module by hand in a browser must run no server (spring.main.web-application-type=none); otherwise the start fails with:
spring_boot_starter_web has no web server on this platform: the web has no server sockets. Run the server on the VM or in a Flutter app on mobile or desktop, or set spring.main.web-application-type=none.
In Spring (Java)
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
server.port=8080
server.address=127.0.0.1
server.servlet.context-path=/shop
Differences that matter:
- The server is
dart:io'sHttpServer, not Tomcat, Jetty or Undertow. HTTP/1.1 only;server.http2.enabledis not read. server.servlet.context-pathisserver.context-path. The old name (any key underserver.servlet.) stops the start and names the new key.server.max-http-request-body-sizeis this starter's own key.spring.main.web-application-typeonly knowsnone. There is noservletorreactive.spring.main.register-shutdown-hookisfalseby default.- A Flutter app listens on
127.0.0.1by default. - There are no
server.tomcat.*,server.jetty.*orserver.undertow.*keys, and noserver.max-http-request-header-size.