JJ Roman
JJ Roman

Reputation: 4570

URI path parameter parsing in Java

One of REST apis I am consuming returning urls in this format:

/api/variables{/id}
/api/projects{/id}{?skip}

The same url pattern seems to be used in JAX-WS implementations in @Path annotation so hopefully there is already some library which can help with this task.

What is the best way to parse url formatted in this way and to populate it with parameters? I would preferably use some library or Java EE core classes, to avoid custom development.

Edit: What I am looking to achieve:

Strnig template = "/api/projects{/id}{?skip}"; // This is provided by REST service
SomeParser sp = new SomeParser(template);
sp.setParam("id", "1a");
sp.setParam("skip", "20");
sp.getUrl(); // Expected output: /api/projects/1a/?skip=20

In the meantime I found URIs are provided in format from RFC6570

The question is: Is there ready to use library that can do that?

Upvotes: 1

Views: 2427

Answers (1)

Luís Soares
Luís Soares

Reputation: 6222

Using JAX-RS:

@Path("/api")
public class RestService {

  @Path("/variables/{id}")
  public List<Variable> getVariables(@PathParam("id") String id), 
                                     @QueryParam("skip") @DefaultValue("false") boolean skip) {
      // ...
  }

  @Path("/projects/{id}")
  public List<Project> getProjects(@PathParam("id") String id) {
      // ...
  }

}

Be aware the / are outside the {}.

Note: Java EE provides only the API. You need to use some implementation.

Upvotes: 0

Related Questions