Search code examples
javarestwebrestlet

Retrieving resource id in Restlet


what's the Restlet equivalent of the following snippet of code I'm using with Jersey:

  @GET
  @Path("{id}")
  @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,MediaType.TEXT_XML})
  public Todo getEntityXMLOrJSON(@PathParam("id") int id)
  {
    ...
  }

I mean, when using Restlet framework I do the following:

public class ContactsApplication extends Application {
    public Restlet createInboundRoot() {
        Router router = new Router(getContext());
        router.attach("/contacts/{contactId}", ContactServerResource.class);
        return router;
    }
}

how do I retrieve contactId in the get method ?


Solution

  • If you define a path parameter when attaching a server resource, you can access its value within this server resource using the method getAttribute, as described below:

    public class ContactServerResource extends ServerResource {
        @Get
        public Contact getContact() {
            String contactId = getAttribute("contactId");
            (...)
        }
    }
    

    You can notice that you can define such elements as instance variables. The following code is a typical implementation of a server resource ContactServerResource:

    public class ContactServerResource extends ServerResource {
        private Contact contact;
    
        @Override
        protected void doInit() throws ResourceException {
            String contactId = getAttribute("contactId");
            // Load the contact from backend
            this.contact = (...)
            setExisting(this.contact != null);
        }
    
        @Get
        public Contact getContact() {
            return contact;
        }
    
        @Put
        public void updateContact(Contact contactToUpdate) {
           // Update the contact based on both contactToUpdate
           // and contact (that contains the contact id)
        }
    
        @Delete
        public void deleteContact() {
           // Delete the contact based on the variable "contact"
        }
    }
    

    Hope it helps you, Thierry