Issue
I'm trying to solve this: How to rewrite URLs with Spring (Boot) via REST Controllers? by creating some kind of "filter" which would be applied to every incoming HTTP request.
The matter is covered by some answers like for this question: Spring Boot Adding Http Request Interceptors
but interface HandlerInterceptor
deals with javax' HttpServletRequest
and HttpServletResponse
which are not as practical as the new class introduced by Spring i.e. the ServerWebExchange
(see the use of setLocation()
in the code below) which appears in an interface whose name sounds promising, org.springframework.web.server.WebFilter
:
So I ended with something like:
@Component
public class LegacyRestRedirectWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
URI origin = exchange.getRequest().getURI();
String path = origin.getPath();
if (path.startsWith("/api/")) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
URI location = UriComponentsBuilder.fromUri(origin).replacePath(path.replaceFirst("/api/", "/rest/")).build().toUri();
response.getHeaders().setLocation(location);
}
return chain.filter(exchange);
}
}
...in the same way people are doing something similar like:
Alas, my filter is never called!!!
The thing is: I am not in a "WebFlux" context (on the contrary to the questions above) because:
- I don't need to, and
- I tried and got the following problems:
Reactive Webfilter is not working when we have spring-boot-starter-web dependency in classpath (but no definitive answer); marked duplicate of: Don't spring-boot-starter-web and spring-boot-starter-webflux work together?
Spring WebFlux with traditional Web Security (I have the "traditional"
spring-boot-starter-security
dependency in mypom.xml
plus a@Configuration
class extendingWebSecurityConfigurerAdapter
- but not willing to migrate it to... what by the way?)
Also I don't understand why would I need to be in a WebFlux context, because org.springframework.web.server.WebFilter
neither deals with reactive
nor Webflux
, right? ..or does it? This is not very clear in the Javadoc.
Solution
In fact, I didn't find a way to make WebFilter
work in a non-WebFlux context, but I could successfully implement such a filter, which both implements javax.servlet.Filter
(non-reactive) AND org.springframework.web.server.WebFilter
(reactive).
Here is my answer to the other related question: https://stackoverflow.com/a/63780659/666414
Answered By - maxxyme