【问题标题】:Spring utility for parsing URIs用于解析 URI 的 Spring 实用程序
【发布时间】:2014-10-13 19:53:25
【问题描述】:

我想使用现有的 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 的倒数,根据我对 Javadocs 的阅读,它没有任何解析功能。

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

这里是:

    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"));

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 2011-06-26
      • 2011-01-31
      • 1970-01-01
      • 2020-11-16
      • 2016-01-22
      • 2023-01-26
      • 2016-07-06
      相关资源
      最近更新 更多