Java Reference
In-Depth Information
Another interesting example is to create a URI from the @Path expressions defined in a JAX-
RS annotated class. Here's an example of a JAX-RS resource class:
@Path ( "/customers" )
public
public class
class CustomerService
CustomerService {
@Path ( "{id}" )
public
public Customer getCustomer ( @PathParam ( "id" ) int
int id ) {...}
}
We can then reference this class and the getCustomer() method within our UriBuilder ini-
tialization to define a new template:
UriBuilder builder = UriBuilder . fromResource ( CustomerService . class );
builder . host ( "{hostname}" )
builder . path ( CustomerService . class , "getCustomer" );
This builder code defines a URI template with a variable hostname and the patterns defined
in the @Path expressions of the CustomerService class and the getCustomer() method.
The pattern would look like this in the end:
http: //{hostname}/customers/{id}
You can then build a URI from this template using one of the build() methods discussed
earlier.
There's also a few peculiarities with this interface. The build(Object..) and
build(Map<String, ?>) methods automatically encode / characters. Take this, for ex-
ample:
URI uri = UriBuilder . fromUri ( "/{id}" ). build ( "a/b" );
This expression would result in:
/ a % 2 Fb
Oftentimes, you may not want to encode the / character. So, two new build() methods were
introduced in JAX-RS 2.0:
public
public abstract
abstract URI build ( Object [] values , boolean
boolean encodeSlashInPath )
throws
throws IllegalArgumentException , UriBuilderException
public
public abstract
abstract URI buildFromMap ( Map < String , ?> values , boolean
boolean encodeSlashInPath )
throws
throws IllegalArgumentException , UriBuilderException
If you set the encodeSlashInPath to false , then the / character will not be encoded.
Search WWH ::




Custom Search