简体   繁体   中英

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

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?

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM