Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring utility for parsing URIs

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.

like image 916
David V Avatar asked Oct 13 '14 19:10

David V


1 Answers

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"));
like image 62
Biju Kunjummen Avatar answered Oct 07 '22 01:10

Biju Kunjummen