What is to prefer in Restlet: handleGet, handlePost OR represent, acceptRepresetation?
IMHO, there are two techiques to handle a query for a resource:
- For http GET you can override
represent(Variant variant)
orhandleGet()
. - For http POST the same applies with
acceptRepresentation(Representation entity)
andhandlePost()
.
The doc for handleGet says:
Handles a GET call by automatically returning the best representation available. The content negotiation is automatically supported based on the client's preferences available in the request. This feature can be turned off using the "negotiateContent" property.
and for represent:
Returns a full representation for a given variant previously returned via the getVariants() method. The default implementation directly returns the variant in case the variants are already 开发者_运维技巧full representations. In all other cases, you will need to override this method in order to provide your own implementation.
What are the main differences between these two types of implementations? In which case should I prefer one over the other? Is it right that I can achieve with e.g. handleGet()
everything that would work with represent()
?
I first started using handleGet
setting the entity for the response. When I implemented another project I used represent
. Looking back i can't really say one way is better or clearer than the other. What are your expirences for that?
I recommend using represent(Variant)
because then you’ll be leveraging the content negotiation functionality provided by the default implementation of handleGet(Request, Response)
.
BTW, lately I've started using the annotation-based syntax instead of overriding superclass methods, and I like it. I find it clearer, simpler, and more flexible.
For example:
@Post('html')
Representation doSearch(Form form) throws ResourceException {
// get a field from the form
String query = form.getFirstValue("query");
// validate the form - primitive example of course
if (query == null || query.trim().length() == 0)
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Query is required.");
// do something
SearchResults searchResults = SearchEngine.doSearch(query);
// return a HTML representation
return new StringRepresentation(searchResults.asHtmlString(), MediaType.TEXT_HTML);
}
The advantages of using this approach include the incoming representation being automatically converted to a useful form, the method can be named whatever makes sense for your application, and just by scanning the class you can see which class methods handle which HTTP methods, for what kind of representations.
精彩评论