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
if I deploy a servlet, but I would like to achieve it with webflux, without having to explicitly add the path to every route or use MVC.
The context path is the name of the URL at which we access the application. The default context path is empty. The context path can be changed in many ways. We can set it in the properties file, with the SERVER_SERVLET_CONTEXT_PATH environment variable, with Java System property, or on the command line.
The context path is the portion of the request URI that is used to select the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "".
Spring WebFlux makes it possible to build reactive applications on the HTTP layer. It is a reactive fully non-blocking, annotation-based web framework built on Project Reactor that supports reactive streams back pressure and runs on non-blocking servers such as Netty, Undertow and Servlet 3.1+ containers.
According to this
There is servlet in the name of the property which should be a hint that won't work with webflux.
With springboot v2.3, you can put this in your properties file
spring.webflux.base-path=/your-path
release-notes reference: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#configurable-base-path-for-webflux-applications
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);
};
}
I was facing a similar issue with the spring.webflux.base-path
(which didn't seem to be working as expected) in webflux-reactive-spring-web
and I realized that I had autoconfiguration disabled.
A manually workaround is:
@Bean
public WebFluxProperties webFluxProperties(){
return new WebFluxProperties();
}
Here's my way of doing it with Tomcat Reactive:
@Configuration
public class TomcatReactiveWebServerConfig extends TomcatReactiveWebServerFactory {
@Value("${server.servlet.context-path}")
private String contextPath;
/**
* {@inheritDoc}
*/
@Override
protected void configureContext(final Context context) {
super.configureContext(context);
if (StringUtils.isNotBlank(this.contextPath)) {
context.setPath(this.contextPath);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With