I\'ve been trying to find a way to set the context path for a webflux application. I know I can configure it using
server.servlet.context-path
For use cases where WebFlux application is behind load balancer/proxy you can use dedicated class - ForwardedHeaderTransformer
that will extract path context from X-Forwarded-Prefix
and will add it to ServerHttpRequest
.
Doing so you won't need to modify global context-path
(which does not make sense in WebFlux)
More about it here: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-web-handler-api
You can use web filter to make WebFlux support contextPath
@Bean
public WebFilter contextPathWebFilter() {
String contextPath = serverProperties.getServlet().getContextPath();
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
if (request.getURI().getPath().startsWith(contextPath)) {
return chain.filter(
exchange.mutate()
.request(request.mutate().contextPath(contextPath).build())
.build());
}
return chain.filter(exchange);
};
}
For Undertow I managed to add a context path by creating a customized UndertowReactiveWebServerFactory:
@Bean
public UndertowReactiveWebServerFactory undertowReactiveWebServerFactory(
@Value("${server.servlet.context-path}") String contextPath) {
return new UndertowReactiveWebServerFactory() {
@Override
public WebServer getWebServer(HttpHandler httpHandler) {
Map<String, HttpHandler> handlerMap = new HashMap<>();
handlerMap.put(contextPath, httpHandler);
return super.getWebServer(new ContextPathCompositeHandler(handlerMap));
}
};
}