我在 Spring Reactive 应用程序中工作。我知道如何使用 HttpServletRequest 在拦截器中获取 PathVariable,有些类似:
request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
但我们必须进行一些更改,现在我们有了 WebFilter 实现,因此我们不使用 HttpServletRequest,而是使用 ServerWebExchange
如何从 ServerWebExchange 获取 Pathvariable?这是可能的?
我认为对此没有直接的解决方案。
您可以执行以下操作:
ServerWebExchange.getRequest()
将返回ServerHttpRequest
对象,这样你就可以提取URI
从像这样的对象:
URI uri = serverHttpRequest.getURI()
然后,使用Uri模板 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriTemplate.html您应该能够提取路径变量值。
这是示例:
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);
这将产生以下输出:
{sectionId=asdf-987, assigmentId=dsfwq98r7sdfg}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)