1

I'm creating a RESTful service for accessing data.

So I started writing that service, first I created a ReadOnlyResource interface with the following code:

public interface ReadOnlyResource<E, K> {
    Collection<E> getAll();
    E getById(K id);
}

Where E is the returned type and K is the key element.

So if I'm implementing with <Integer, Integer> I'll inject the key like t

@GET
@Path("/{id}")
@Override
public Integer getById(@PathParam("id") Integer id) {
    return null;
}

But when my key is more complex, like this:

public class ComplexKey {
    private String name;
    private int value;
}

How can I inject this so I can use my interface?

Is there a way to inject both params and create the key with them?

EDIT: the solution of @QueryParam doesn't help because what I try to reach is going to /some name/some number and receive a ComplexKey instance which contains the some name and some number values from the url.

  • Possible duplicate of [Passing custom type query parameter](http://stackoverflow.com/questions/30403033/passing-custom-type-query-parameter) – zloster Apr 03 '17 at 08:05
  • Not exactly, when I wanted is a way that I can implement it with my current interface, the must be 1 argument passed to the method. –  Apr 03 '17 at 08:48

2 Answers2

3

what I try to reach is going to /some name/some number and receive a ComplexKey instance which contains the some name and some number values from the url

Use a @BeanParam

public class ComplexKey {
    @PathParam("name")
    private String name;
    @PathParam("value")
    private int value;
    // getters/setters
}

@Path("/{name}/{value}")
getById(@BeanParam ComplexKey key)
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

AFAIK, you can have Objects as @PathParam, if you have a Constructor that i.e. parses a String, like:

public class ComplexKey {
    private String name;
    private int value;
    
    public ComplexKey(String stringValue) {
        // parse the stringValue and assign name and value
    }
}

Or as an Alternative, you can use a static method fromString for the conversion:

public static ComplexKey fromString(stringValue) {…}

@GET
@Path("/{complexId}")
@Override
public Integer getById(@PathParam("complexId") ComplexId complexId) {
    return null;
}

The call then could look like: http://localhost:8080/api/John-25

Stuepfnick
  • 71
  • 5