Java Reference
In-Depth Information
package com.soacookbook;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.ProduceMime;
import javax.ws.rs.ConsumeMime;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
/**
* API for Products.
*/
@Path("/products/{id}")
public class ProductResource {
@Context
private UriInfo context;
/** Creates a new instance of ProductResource */
public ProductResource() { }
@GET
@ProduceMime("text/plain")
public String getProduct(@PathParam("id") int productId) {
switch (productId) {
case 1: return "A Shiny New Bike";
case 2: return "Big Wheel";
case 3: return "Taser: Toddler Edition";
default: return "No such product";
}
}
}
Building this class into a WAR with the Jersey JARs and the servlet mapping in the web.xmlis
all you need to do to deploy this example. The string value of the template must make a valid
URI path. If you open a browser to http://localhost:8080/JaxrsExamples/resources/products/3 ,
you should see this response:
Taser: Toddler Edition
Obviously, in the real world you would go to a database delegate or something here to get
the product info. The only trick to this example is that the value you pass to the @PathParam
annotation must match the text inside the curly braces that define your template in the @Path
annotation, as that's what provides the necessary mapping.
Search WWH ::




Custom Search