Earthly Powers
- All
- Fast Infoset
- General
- Java
- REST
Resourcegroovy
The following is a resource written in Groovy using Jersey and the 311 API:
@UriTemplate("/test")
@ProduceMime(["text/html"])
public class MyResource {
@HttpContext UriInfo uriInfo;
@HttpMethod
def getString() {
def writer = new StringWriter()
def html = new MarkupBuilder(writer)
html.html {
head {
title("Groovy resource with 311 and Jersey")
}
body {
h1("URI: " + uriInfo.getURI())
}
}
return writer.toString()
}
@UriTemplate("subresource")
@HttpMethod
def getSubResourceString() {
def writer = new StringWriter()
def html = new MarkupBuilder(writer)
html.html {
head {
title("Sub-resource")
}
body {
h1("URI of sub-resource: " + uriInfo.getURI())
}
}
return writer.toString()
}
}
Groovy 1-1-beta-1 supports Java annotations on classes, fields and methods, but not yet on method parameters (I could not get it to work so that the field uriInfo is an annotated method parameter instead). The above example combines 311 annotated methods with the Groovy markup builder to spit out HTML.
I wrote another Groovy class to deploy MyResource using the Light Weight HTTP server:
public class Main {
static void main(String[] args) {
def handler = ContainerFactory.createContainer(
HttpHandler.class,
MyResource.class);
def server = HttpServer.create(
new InetSocketAddress(9998), 0);
server.createContext("/service", handler);
server.setExecutor(null);
server.start();
System.in.read();
}
}
So just like with Scala it is possible to use Jersey with Groovy on the Java Virtual Machine.
Posted at 01:57PM Jun 29, 2007 by Paul Sandoz in REST | Comments[0]