Java - Better way to parse a RESTful resource URL

dsw88 picture dsw88 · Jul 24, 2013 · Viewed 10.6k times · Source

I'm new to developing web services in Java (previously I've done them in PHP and Ruby). I'm writing a resource that is of the following format:

<URL>/myService/<domain>/<app_name>/<system_name>

As you can see, I've got a three-level resource identifier, and I'm trying to figure out the best way to parse it. The application I'm adding this new service to doesn't make use of Jersey or any RESTful frameworks like that. Instead, it's just extending HttpServlet.

Currently they're following an algorithm like this:

  • Call request.getPathInfo()
  • Replace the "/" characters in the path info with "." characters
  • Use String.substring methods to extract individual pieces of information for this resource from the pathInfo string.

This doesn't seem very elegant to me, and I'm looking for a better way. I know that using the javax.ws.rs package makes this very easy (using @Path and @PathParam annotations), but using Jersey is probably not an option.

Using only the base HttpServletRequest object and standard Java libraries, is there a better way to parse this information than the method described above?

Answer

Dongho Yoo picture Dongho Yoo · Feb 5, 2014

How about jersey UriTemplate?

import com.sun.jersey.api.uri.UriTemplate;

...

String path = "/foos/foo/bars/bar";

Map<String, String> map = new HashMap<String, String>();
UriTemplate template = new UriTemplate("/foos/{foo}/bars/{bar}");
if( template.match(path, map) ) {
    System.out.println("Matched, " + map);
} else {
    System.out.println("Not matched, " + map);
}