-
Notifications
You must be signed in to change notification settings - Fork 1
REST Documentation
gibello edited this page Dec 14, 2011
·
7 revisions
Based on java servlets. Packages : cades.icar.rest.servlet and cades.icar.rest.resource.
The developer extends the cades.icar.rest.resource.RestResource class, that includes the following methods (corresponding to HTTP methods commonly used by REST):
- String onGet(String operation, RequestContext ctx)
- String onPost(String operation, RequestContext ctx)
- String onPut(String operation, RequestContext ctx)
- String onDelete(String operation, RequestContext ctx)
Example:
package cades.icar.rest.sample;
import cades.icar.rest.resource.RestResource;
import cades.icar.rest.servlet.RequestContext;
public class DisplayNameResource extends RestResource {
public DisplayNameResource(String name) {
super(name);
setContentType("text/html");
}
/**
* HTTP GET method
* URL may end with /<name> or provide HTTP parameter name=<name>
*/
@Override
public String onGet(String operation, RequestContext ctx) {
String name = ctx.getServletRequest().getParameter("name");
if(name == null) name = operation;
return (name != null && name.length()>=1
? "Hello, " + name
: "What's your name ?");
}
@Override
public String onPost(String operation, RequestContext ctx) {
return onGet(operation, ctx);
}
}
Then, the extended class is registered in the ResourceRegistry : it may be done by extending the cades.icar.rest.servlet.SimpleRestServlet class and overloading the initRestResources(ResourceRegistry registry) method (see below):
package cades.icar.rest.sample;
import cades.icar.rest.resource.ResourceRegistry;
import cades.icar.rest.servlet.SimpleRestServlet;
/**
* Servlet implementation class DemoRestServlet
*/
public class DemoRestServlet extends SimpleRestServlet {
private static final long serialVersionUID = 1L;
@Override
public void initRestResources(ResourceRegistry registry) {
// Provide resource handler for "/demo/greetings"
registry.registerResource("demo",
new DisplayNameResource("greetings"));
}
}
The so-overloaded servlet may then be declared in WEB-INF/web.xml, as for any webapp, for example as follows:
<servlet>
<servlet-name>DemoRestServlet</servlet-name>
<servlet-class>cades.icar.rest.sample.DemoRestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoRestServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>