In the last segment of this series I pointed you to use a couple of resources from my github as templates, but didn’t really specify how those work or how to add your own services. I hope to finish the series today with some explanation of those resources.
The Web.xml is the configuration in all Java EE apps. It basically sets up the configuration for the application. The application I have specified has a single servlet, which is defined by the wink framework.
So your application will need a class that extends it. In the web.xml its specified in the init-param
The web.xml also has a servlet mapping basically specifies what url the servlet will live at. In the example it is “/rest*/ which basically means if the url has that pattern in it it will call the servlet and pass in the rest of the url for routing.
This is the aforementioned class that is referenced in the web.xml. The only thing it really does is overrides the getClasses Method and returns back a Set of classes that contain Resources which are basically the rest services that are defined.
This is basically the meat of the service. It specifies two methods one for a GET request annotated by the @GET above it and one for a POST request, annotated by the @POST above it. So in this class we specify what URL it will live at with the annotation above the class declaration
JAX-RS methods need to return a “javax.ws.rs.core.Response” object. We are creating and returning this object in both of these methods, JAX-RS has some nifty functionality for sending back different http codes and http headers. For instance you can see in the getMessage method I am returning back a 200 http status code with a content-type http header of application/json
ResponseBuilder builder = Response.ok(jjo.toString(), MediaType.APPLICATION_JSON);
JAX-RS is the standard way of doing REST services in the Java EE world, so there are all kinds of plugins and documentation/blogs out there with tips and tricks of how to use it once you have it setup. I would recommend the java doc and the tutorial from Oracle on how to get started for some beginner lessons. I know sometimes writing a xAgent or even a plain old agent is quicker, but to ensure that your code is decoupled and will even work outside of an XPages context this is probably your best way of creating a rest service. Even IBM realized this as this is how DAS services is built in Domino.