Java Reference
In-Depth Information
@GET
@Produces("text/xml")
public String getProducts(
@PathParam("id") int productId,
@QueryParam("results")
@DefaultValue("5") int numResults) {
StringBuilder result = new StringBuilder("<products>");
//return the number of results requested
for (int i = 0; i < numResults; i++) {
result.append("<p>Product " + i + "</p>");
}
result.append("</products>");
return result.toString();
}
}
In this example, you have a loop that runs to create the number of product results the user
wants to see in this search. The numResults integer is declared in the method signature and
annotated with @QueryParam to indicate that it should receive the value from the browser
address's query parameter called results . This value will be coerced into an integer; if the
runtime can't do that, it will throw a 404 exception. You then fake out a search and loop, ap-
pending to the result the number of rows the user asked for.
Accessing this resource with the URL http://localhost:8080/restexamples/resources/
products?results=3 gives the following XML result:
<products><p>Product 0</p><p>Product 1</p><p>Product 2</p></products>
If you access it without the query parameter, you get 5 product results, as specified by the
@DefaultValue annotation.
Search WWH ::




Custom Search