Java Reference
In-Depth Information
The
@javax.ws.rs.Consumes
annotation applied to
createCustomer()
specifies which
media type the method is expecting in the message body of the HTTP input request. If the
client POSTs a media type other than XML, an error code is sent back to the client.
The
createCustomer()
method takes one
java.io.InputStream
parameter. In JAX-RS,
any non-JAX-RS-annotated parameter is considered to be a representation of the HTTP input
request's message body. In this case, we want access to the method body in its most basic
form, an
InputStream
.
WARNING
Only one Java method parameter can represent the HTTP message body. This means any other para-
meters must be annotated with one of the JAX-RS annotations discussed in
Chapter 5
.
The implementation of the method reads and transforms the POSTed XML into a
Customer
object and stores it in the
customerDB
map. The method returns a complex response to the
client using the
javax.ws.rs.core.Response
class. The static
Response.created()
meth-
od creates a
Response
object that contains an HTTP status code of 201, “Created.” It also
adds a
Location
header to the HTTP response with the value of something like
ht-
tp://shop.restfully.com/customers/333
, depending on the base URI of the server and the gen-
erated ID of the
Customer
object (333 in this example).
Retrieving customers
@GET
@Path
(
"{id}"
)
@Produces
(
"application/xml"
)
public
public
StreamingOutput
getCustomer
(
@PathParam
(
"id"
)
int
int
id
) {
final
final
Customer customer
=
customerDB
.
get
(
id
);
iif
(
customer
==
null
null
) {
throw
throw new
new
WebApplicationException
(
Response
.
Status
.
NOT_FOUND
);
}
return
return new
new
StreamingOutput
() {
public
public
void
void
write
(
OutputStream outputStream
)
throws
throws
IOException
,
WebApplicationException
{
outputCustomer
(
outputStream
,
customer
);
}
};
}
We annotate the
getCustomer()
method with the
@javax.ws.rs.GET
annotation to bind
HTTP GET operations to this Java method.
