Spring MVC 用于解析URI的Spring实用程序

nsc4cvqm  于 2022-11-14  发布在  Spring
关注(0)|答案(3)|浏览(153)

我想使用现有的Spring功能从URL中提取路径变量和查询参数。我有一个对MVC @RequestMappingUriComponentsBuilder有效的路径格式字符串。我还有一个实际路径。我想从该路径中提取路径变量。
比如说。

String format = "location/{state}/{city}";
String actualUrl = "location/washington/seattle";
TheThingImLookingFor parser = new TheThingImLookingFor(format);
Map<String, String> variables = parser.extractPathVariables(actualUrl);
assertThat(variables.get("state", is("washington"));
assertThat(variables.get("city", is("seattle"));

它有点像UriComponentsBuilder的逆,从我对Javadoc的阅读来看,它没有任何解析特性。

8yoxcaq7

8yoxcaq71#

这就是:

String format = "location/{state}/{city}";
    String actualUrl = "location/washington/seattle";
    AntPathMatcher pathMatcher = new AntPathMatcher();
    Map<String, String> variables = pathMatcher.extractUriTemplateVariables(format, actualUrl);
    assertThat(variables.get("state"), is("washington"));
    assertThat(variables.get("city"), is("seattle"));
rnmwe5a2

rnmwe5a22#

首先要看的是org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver的源代码,这是MVC中@PathVariable注解所使用的解析器。查看方法“resolveName”,了解Spring代码在做什么。从那里你应该能够找到MVC正在使用的类。然后你可以看看是否可以使它满足你的要求。

xghobddn

xghobddn3#

我也遇到过同样的问题,并遇到了这个相当古老的问题。现在和8年后,你也可以使用PathPatternParser。它是可用的since version 5.0。要了解更多信息和AntPathMatcher的比较,请参阅spring.io的博客文章。

var format = "location/{state}/{city}";
var actualUrl = "location/washington/seattle";
var parser = new PathPatternParser();
var pp = parser.parse(format);
var info = pp.matchAndExtract(PathContainer.parsePath(actualUrl));
System.out.println(info.getUriVariables().get("state")); // washington
System.out.println(info.getUriVariables().get("city")); // seattle

希望这对某人还有帮助!

相关问题