Java – The netty context path for spring boot

The netty context path for spring boot… here is a solution to the problem.

The netty context path for spring boot

I’m using Spring Boot with WebFlux and removed the embedded Tomcat dependency from Starter Web, I want to add a base context path to my app, is there any way to do that? I need this because I have the ingrees attribute behind the kubernetes cluster and the redirection is based on the context path.

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
    <exclusion>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
    </exclusions>

Solution

You cannot use Spring Web and Spring Webflux dependencies at the same time. If you do, Spring will prioritize Spring Web and the Webflux filter will not load at startup.

During startup, spring attempts to create the correct ApplicationContext for you. As written here Spring boot Web Environment If Spring MVC (web) is on the classpath, it will take precedence over this context.

A Spring Boot application is either a traditional Web application or a WebFlux application. You can’t do both.

ContextPath is not something used in reactive programming, so you have to filter each request and rewrite the path of each request.

This should work, it’s a component webfilter, which intercepts each request and then adds the context path you defined in application.properties

@Component
public class ContextFilter implements WebFilter {

private ServerProperties serverProperties;

@Autowired
    public ContextFilter(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

@Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        final String contextPath = serverProperties.getServlet().getContextPath();
        final 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);
    }
}

But this only works if your application is loaded as a Spring Responsive application.

Related Problems and Solutions