Java Reference
In-Depth Information
Subresource Locators
So far, I've shown you the JAX-RS capability to statically bind URI patterns expressed
through the @Path annotation to a specific Java method. JAX-RS also allows you to dynam-
ically dispatch requests yourself through subresource locators. Subresource locators are Java
methods annotated with @Path , but with no HTTP method annotation, like @GET , applied to
them. This type of method returns an object that is, itself, a JAX-RS annotated service that
knows how to dispatch the remainder of the request. This is best described using an example.
Let's continue by expanding our customer database JAX-RS service. This example will be a
bit contrived, so please bear with me. Let's say our customer database is partitioned into dif-
ferent databases based on geographic regions. We want to add this information to our URI
scheme, but we want to decouple finding a database server from querying and formatting
customer information. We will now add the database partition information to the URI pattern
/customers/{database}-db/{customerId} . We can define a CustomerDatabaseRe-
source class and have it delegate to our original CustomerResource class. Here's the ex-
ample:
@Path ( "/customers" )
public
public class
class CustomerDatabaseResource
CustomerDatabaseResource {
@Path ( "{database}-db" )
public
public CustomerResource getDatabase ( @PathParam ( "database" ) String db ) {
// find the instance based on the db parameter
CustomerResource resource = locateCustomerResource ( db );
return
return resource ;
}
protected
protected CustomerResource locateCustomerResource ( String db ) {
...
}
}
The CustomerDatabaseResource class is our root resource. It does not service any HTTP
requests directly. It processes the database identifier part of the URI and locates the identified
customer database. Once it does this, it allocates a CustomerResource instance, passing in a
reference to the database. The JAX-RS provider uses this CustomerResource instance to
service the remainder of the request:
public
public class
class CustomerResource
CustomerResource {
private
private Map < Integer , Customer > customerDB =
new
new ConcurrentHashMap < Integer , Customer >();
private
private AtomicInteger idCounter = new
new AtomicInteger ();
Search WWH ::




Custom Search