Java Reference
In-Depth Information
public
public
UriBuilder
getRequestUriBuilder
();
public
public
URI
getAbsolutePath
();
public
public
UriBuilder
getAbsolutePathBuilder
();
public
public
URI
getBaseUri
();
public
public
UriBuilder
getBaseUriBuilder
();
For example, let's say you have a JAX-RS service that exposes the customers in a customer
database. Instead of having a base URI that returns all customers in a document, you want to
embed
previous
and
next
links so that you can navigate through subsections of the data-
base (I described an example of this earlier in this chapter). You will want to create these link
relations using the URI to invoke the request:
@Path
(
"/customers"
)
public
public class
class
CustomerService
CustomerService
{
@GET
@Produces
(
"application/xml"
)
public
public
String getCustomers
(
@Context
UriInfo uriInfo
) {
UriBuilder nextLinkBuilder
=
uriInfo
.
getAbsolutePathBuilder
();
nextLinkBuilder
.
queryParam
(
"start"
,
5
);
nextLinkBuilder
.
queryParam
(
"size"
,
10
);
URI next
=
nextLinkBuilder
.
build
();
...
set up the rest of the document
...
}
To get access to a
UriInfo
instance that represents the request, we use the
@javax.ws.rs.core.Context
annotation to inject it as a parameter to the JAX-RS resource
method
getCustomers()
. Within
getCustomers()
, we call
ur-
iInfo.getAbsolutePathBuilder()
to obtain a preinitialized
UriBuilder
. Depending on
how this service was deployed, the URI created might look like this:
http:
//example.com/jaxrs/customers?start=5&size=10
UriInfo
also allows you to relativize a URI based on the current request URI.
public
public
URI
relativize
(
URI uri
);
So, for example, if the current request was
http://localhost/root/a/b/c
and you passed
a/d/e
as a parameter to the
relativize()
method, then the returned URI would be
../../
d/e
. The
root
segment is the context root of your JAX-RS deployment. Relativization is
based off of this root.