Search code examples
javamicronaut

How to get a request path variable within a Filter? [Micronaut 1.3.2]


Usually in Spring we can retrieve the path variable with:

final Map<String, String> pathVariables = (Map<String, String>) request
                 .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

Here is what I do so far.

Controller:

@Get(value = "/{variable}/anotherpath")
public Single<HttpResponse<ResponseESQ>> myController(String variable)  {}

Filter :

@Filter("/**")
public class myFilter implements HttpServerFilter {
  @Override
  public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) { 
    // I need here to consume the path variable
    request.getAttribute("variable")
  }
}

I try to use : request.getAttributes() but it doesn't work.

How can we do the same in Micronaut?


Solution

  • Given the following controller with an URI that contains two path variables something and name.

    @Controller("/say")
    public class SuperController {
    
      @Get("{something}/to/{name}")
      @Produces
      public String hello(String something, String name) {
        return String.format("%s %s", something, name);
      }
    }
    

    You can write a filter that can access the path variables by accessing the io.micronaut.web.router.UriRouteMatch that is contained in io.micronaut.http.HttpMessage#getAttributes.

    The following example filter accesses the path variables.

    @Filter("/**")
    public class SuperFilter implements HttpFilter {
      @Override
      public Publisher<? extends HttpResponse<?>> doFilter(HttpRequest<?> request, FilterChain chain) {
        Optional<UriRouteMatch> uriRouteMatch = request
            .getAttributes()
            .get(HttpAttributes.ROUTE_MATCH.toString(), UriRouteMatch.class);
    
        if (uriRouteMatch.isPresent()) {
          // access the path variables.
          Map<String, Object> variableValues = uriRouteMatch.get().getVariableValues();
          System.out.println(variableValues);
        }
        return chain.proceed(request);
      }
    }
    

    Hope this answers your question. Good luck and have fun with Micronaut.