Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Better way to parse a RESTful resource URL

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?

like image 265
dsw88 Avatar asked Jul 24 '13 17:07

dsw88


People also ask

What is recommended method and URL pattern for retrieving a specific user?

What is the recommended method and URL pattern for retrieving a specific user? GET /user/{id} GET /users/{id}

What URL pattern is used when writing a RESTful API?

A RESTful web service request contains: An Endpoint URL. An application implementing a RESTful API will define one or more URL endpoints with a domain, port, path, and/or query string — for example, https://mydomain/user/123?format=json .

Which URL pattern is recommended when working with one resources and a collection of resources?

URL Structure The recommended convention for URLs is to use alternate collection / resource path segments, relative to the API entry point.


1 Answers

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);
}       
like image 127
Dongho Yoo Avatar answered Nov 14 '22 22:11

Dongho Yoo