8

I would like to extract path variables and query parameters from a URL using existing Spring features. I have a path format string which is valid for an MVC @RequestMapping or UriComponentsBuilder. I also have an actual path. I would like to extract path variables from that path.

For example.

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

It is something like the inverse of UriComponentsBuilder, which from my reading of the Javadocs does not have any parsing features.

David V
  • 11,531
  • 5
  • 42
  • 66
  • Could this help point you in the right direction: [Spring 3 RequestMapping: Get path value](http://stackoverflow.com/questions/3686808/spring-3-requestmapping-get-path-value)? – Mr. Polywhirl Oct 13 '14 at 20:01

3 Answers3

17

Here it goes:

    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"));
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
1

I had the same problem and came across this rather old question. Nowadays and 8 years later you can also use PathPatternParser. It's available since version 5.0. For more information and a comparison to AntPathMatcher see the blog post from 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

Hope this still helps someone!

zemirco
  • 16,171
  • 8
  • 62
  • 96
0

The first place to look is in the source code for org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver this is the resolver used for the @PathVariable annotation in MVC. Look at the method "resolveName" to see what the Spring code is doing. Form there you should be able to find the class that MVC is using. Then you can see if you can make it meet your requirements.

Mark.ewd
  • 694
  • 1
  • 8
  • 22