Home > Blockchain >  How to get path variable in an implementation of WebFilter? (ServerWebExchange)
How to get path variable in an implementation of WebFilter? (ServerWebExchange)

Time:06-25

Im working in a Spring Reactive application. I know how get a PathVariable in a interceptor with HttpServletRequest, some like that:

request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 

But we had to make some changes and now we have a WebFilter implementation, so we don't use HttpServletRequest, instead we use ServerWebExchange

How can I get a Pathvariable from ServerWebExchange? Its possible?

CodePudding user response:

I think there is no straightforward solution to that.

What you can do is the following :

ServerWebExchange.getRequest() will return ServerHttpRequest object, so you can extract URI from that object like this:

URI uri = serverHttpRequest.getURI()

Then, using UriTemplate you should be able to extract path variable values.

Here is example:

URI uri = new URI("abc.api.com/learn/sections/asdf-987/assignments/dsfwq98r7sdfg"); //suppose that your URI object is something like this
        String path = uri.getPath(); //get the path
        UriTemplate uriTemplate = new UriTemplate("/learn/sections/{sectionId}/assignments/{assigmentId}"); //create template
        Map<String, String> parameters = new HashMap<>();
        parameters = uriTemplate.match(path); //extract values form template
        System.out.println(parameters);

This will produce following output:

 {sectionId=asdf-987, assigmentId=dsfwq98r7sdfg}
  • Related