如何在 WebFilter 的实现中获取路径变量?(服务器网络交换)

Nah*_*ani 2 java spring reactive spring-webflux

我在 Spring Reactive 应用程序中工作。我知道如何使用 HttpServletRequest 在拦截器中获取 PathVariable,有些类似:

request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 
Run Code Online (Sandbox Code Playgroud)

但我们必须进行一些更改,现在我们有了 WebFilter 实现,因此我们不使用 HttpServletRequest,而是使用 ServerWebExchange

如何从 ServerWebExchange 获取 Pathvariable?这是可能的?

Nem*_*nja 7

我认为对此没有直接的解决方案。

您可以执行以下操作:

ServerWebExchange.getRequest()将返回对象,因此您可以像这样从该对象中ServerHttpRequest提取:URI

URI uri = serverHttpRequest.getURI()

然后,使用UriTemplate您应该能够提取路径变量值。

这是示例:

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);
Run Code Online (Sandbox Code Playgroud)

这将产生以下输出:

 {sectionId=asdf-987, assigmentId=dsfwq98r7sdfg}
Run Code Online (Sandbox Code Playgroud)