I've got a REST service set up to access information stored in a database.
I'd like to be able to access based on either an item's id
or name
.
So lets say I've got a record
name | id | description
mine | 65 | "my thing"
I'd like to be able to access this item through either:
myurl.com/items/65
myurl.com/items/mine
I'm using Jersey (Java library). Is there a way I can define the PathParam to accept either an int or a String WITHOUT using object.typeOf()?
I'd like to avoid this:
@PATH("/items/{identifier}
@GET
public String getItem(@PathParam("identifier") Object identifier){
if(identifier.typeOf().equals(String.typeOf()))....
}
Thanks
If you're looking for a "clean" solution - I don't think there is one. But you could do this:
@PATH("/items/{identifier}")
public String getItem(@PathParam("identifier") String identifier){
try {
return getByID( Long.parseLong(identifier) );
} catch (NumberFormatException ex) {
return getByName( identifier );
}
}
Also, this won't compile - there's no such method as typeOf()
:
if(identifier.typeOf().equals(String.typeOf()))
I think you meant:
if (identifier instanceof String)
EDIT: And anyway, your original idea (setting the parameter type to Object
, then checking for the exact instance type) won't work; the container has no way of knowing that the path element may be an integer, so it won't attempt to parse it as an integer, and it'll just give you a String
every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With