Java Reference
In-Depth Information
for(Product product:productList){
xmlstring.append("<product>");
xmlstring.append("<id>" + product.getId() + "</id>");
xmlstring.append("<name>" + product.getName() + "</name>");
xmlstring.append("<description>" + product.getDescription() + "</description>");
xmlstring.append("</product>");
}
return xmlstring.toString();
}
The
@GET
annotation designates this as a resource method that will be utilized for obtaining data. When the
specified URI that is designated within the
@Path
annotation is visited, this method will be invoked, producing XML
content.
Consuming Content
Annotate resource methods within a JAX-RS class with
@POST
or
@PUT
to indicate that some content is being passed to
the method. The following briefly summarizes the different HTTP methods that can be used for consuming content:
•
POST
updates an existing resource or creates a new resource.
•
PUT
creates a new idempotent resource.
To specify the type of content being passed, annotate the same method with
@Consumes(content-type)
.
The following excerpt demonstrates the use of
@Consumes
:
@Path("simplerest")
public class SimpleRest {
...
@PUT
@Path("add")
@Consumes("text/plain")
public String add(@QueryParam("text") String text){
this.message = text;
return message;
}
...
}
Note that the
add
method specifies the
@Path
annotation, so it becomes accessible by appending the
add
string to
the URI that was specified in the class's
@Path
. To input a new message stating
Java
, you would visit a URL using the
following format in your browser, which would pass the new message to the
text
variable:
■
Note
for the list of different content types that can be produced or consumed, please refer to table
8-2
.