6.20 resource
'resource' is used for adding subclasses of org.restlet.resource.Resource to the routing.
Both
org.restlet.resource.Resource
and org.restlet.Restlet (as
supported by the
- a higher-level API
- a new instance is created for each request, so Resource's don't need to be thread-safe
Typically the Restlet class will be used for more system/infrastructure-level
work, while the Resource class should be used for everyday resource
implementation work. An alternative for Resource is the
Parameters
(There are parameters available to implement resources inline in the routing using closures, but we recommend using ofClass/ofBean instead)
Example
The following example of a Resource implementation is stolen from the Restlet project:
package org.restlet.example.book.restlet.ch4;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;
public class HelloWorldResource extends Resource {
public HelloWorldResource() {
// A default constructor is required in this case.
}
public void init(Context context, Request request,Response response) {
super.init(context, request, response);
// Declare all kind of representations supported by the resource
getVariants().add(new Variant(MediaType.TEXT_PLAIN));
}
@Override
public Representation represent(Variant variant) throws ResourceException {
Representation representation = null;
// Generate the right representation according to the variant.
if (MediaType.TEXT_PLAIN.equals(variant.getMediaType())) {
representation = new StringRepresentation("hello, world",
MediaType.TEXT_PLAIN);
}
return representation;
}
}
It is attached to a router as follows:
router {
resource(uri: "/helloworld",
ofClass: "org.restlet.example.book.restlet.ch4.HelloWorldResource")
}
Previous