简体   繁体   English

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

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

Im working in a Spring Reactive application.我在 Spring Reactive 应用程序中工作。 I know how get a PathVariable in a interceptor with HttpServletRequest, some like that:我知道如何使用 HttpServletRequest 在拦截器中获取 PathVariable,如下所示:

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但是我们必须做一些改变,现在我们有了一个 WebFilter 实现,所以我们不使用 HttpServletRequest,而是使用 ServerWebExchange

How can I get a Pathvariable from ServerWebExchange?如何从 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: ServerWebExchange.getRequest()将返回ServerHttpRequest对象,因此您可以从该对象中提取URI ,如下所示:

URI uri = serverHttpRequest.getURI()

Then, using UriTemplate you should be able to extract path variable values.然后,使用UriTemplate您应该能够提取路径变量值。

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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