Dec 17, 2008

Misusing Restlet as a Lightweight Alternative to Servlets

I was struck by just how easy (and how lightweight!!) using Restlet was for processing simple HTTP requests:

...
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8080);
component.getDefaultHost().attachDefault(new Restlet() {
public void handle(Request request, Response response) {
Map parameters = request.getResourceRef().getQueryAsForm().getValuesMap();
// fun with parameters here
}
});
component.start();
Isn't that sweet?! No web.xml, no context.xml, very very fast spin-up time, multi-threading out of the box, 200 status by default, 500 status by default on exception, no session junk. Nice.

The only real gotcha was that you seem to have to provide some sort of response (which is probably a good idea anyway). If you don't you get server shutdown complaints in your log (even though it still continues to do the right thing). You can respond with plain text like this:
response.setEntity( "some response text", MediaType.TEXT_PLAIN );

1 comments:

patrickdlogan said...

Yeah, restlet though has several ways to define how the response entity is established. I think the options in the last several releases have increased almost too much. It's not nearly as simple as it was a year ago. But still has the ability to write just a little code and get a lot of restful/http behavior out of it. In short, I love restlet.