Friday, February 22, 2013

Using UriTemplate to change path parameters in a URI

I have been recently working on a client generator in the project and I was solving a bug where I wanted to change path parameter on a URI. This turned out to be quite easy with existing classes that are part of the Jersey project.

First of all you need a instance of UriTemplate, depending on the very of Jersey this is in a slightly different package - you IDE's automatic import will do the work for you.

  String template = "{name}/age/{age}";
  UriTemplate uriTemplate = new UriTemplate(template);

Then you use match(...) to extract them:

  String uri = "";
  Map<String, String> parameters = new HashMap<>();

  // Not this method returns false if the URI doesn't match, ignored
  // for the purposes of the this blog.
  uriTemplate.match(uri, parameters);

Then you can replace the parameters at will and rebuild the URI:


  UriBuilder builder = UriBuilder.fromPath(template);
  URI output =;

No comments: