Extreme Java When vanilla Java is not enough

18Aug/100

Simple REST WS in Java

It's really simple to do REST Webservices using JavaEE 6. Create an class that extends Application with an ApplicationPath annotation:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
 
@ApplicationPath("rest")
public class ApplicationConfig extends Application {
}

Then, use proper annotations to publish your REST services:

import javax.ws.rs.FormParam;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
 
@Path("test")
public class TestREST {
  @GET
  @Produces("application/xml")
  public Result noParms() {
    return new Result(1, "OK");
  }
  @GET
  @Path("/{p}")
  @Produces("application/xml")
  public Result oneParameter(
      @PathParam("p") String parm) {
    return new Result(1, "Hi, " + parm);
  }
  @POST
  @Produces("application/xml")
  public Result twoParms(
      @FormParam("n") String name,
      @FormParam("s") String sname) {
    return new Result(2, sname + ", " + name);
  }
}

Invoke with simple GET request (like "http://server/myapp/rest/test/Bro") or an HTML POST form. "Result" is a simple POJO with JAXB annotations.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)


*

No trackbacks yet.