Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

netty context path for spring boot

I am using spring boot with webflux and removed embedded tomcat dependency from starter web , I wanted to add base context path for my application , is there any way i can do ?? I need this because i have ingrees properties behind kubernetes cluster and redirection is made based on 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>
like image 657
prasannajoshi Avatar asked Nov 27 '25 19:11

prasannajoshi


1 Answers

You cannot use spring web and spring webflux dependencies at the same time. If you do, spring will prioritize spring web and webflux filters will not be loaded at startup.

During startup spring tries to create the correct ApplicationContext for you. As written here Spring boot Web Environment if Spring MVC (web) is on the classpath, it will prioritize this context.

A spring boot application is either a traditional web application, OR it's a webflux application. It cannot be both.

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

This should work, its a component webfilter that intercepts every request and then adds the context path that you define 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 will only work if your application is loaded as a Spring reactive application.

like image 127
Toerktumlare Avatar answered Nov 29 '25 08:11

Toerktumlare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!