By RESTful way, we have to deliver correct resources to a client request, cccording to the context. For example, if the request is “/users/{uid}”, we will list information about the user that has ID=uid and if the request = “/users/{uid}/items/”, the list of items bought by the {uid} has to be listed. This tutorial try to make the resource routing clear.
package forthREST; import org.restlet.Component; import org.restlet.data.Protocol; public class RESTDistributor { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // Create a new Restlet component and add a HTTP server connector to it Component component = new Component(); component.getServers().add(Protocol.HTTP, 8182); // Attach the application to the component and start it component.getDefaultHost().attach(new RouterApplication()); component.start(); } }
package forthREST; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; public class RouterApplication extends Application{ /** * Creates a root Restlet that will receive all incoming calls. */ @Override public synchronized Restlet createInboundRoot() { // Create a router Restlet that routes each call to a new respective instance of resource. Router router = new Router(getContext()); // Defines only two routes router.attach("/users/{uid}", UserResource.class); router.attach("/users/{uid}/items", UserItemResource.class); return router; } }
package forthREST; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class UserResource extends ServerResource { @Get public String toString() { String uid = (String) getRequestAttributes().get("uid"); return "Information about user \"" + uid + "\" is: <nothing>"; } }
package forthREST; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class UserItemResource extends ServerResource { @Get public String toString() { String uid = (String) getRequestAttributes().get("uid"); return "The items that user \"" + uid + "\" bought are: <nothing>"; } }