Java Reference
In-Depth Information
how JAX-RS works in the context of a Java EE (Enterprise Edition) application and things
like JPA.
CustomerResource: Our JAX-RS Service
Now that we have defined a domain object that will represent our customers at runtime, we
need to implement our JAX-RS service so that remote clients can interact with our customer
database. A JAX-RS service is a Java class that uses JAX-RS annotations to bind and map
specific incoming HTTP requests to Java methods that can service these requests. While
JAX-RS can integrate with popular component models like Enterprise JavaBeans (EJB),
Web Beans, JBoss Seam, and Spring, it does define its own lightweight model.
In vanilla JAX-RS, services can either be singletons or per-request objects. A
singleton
means that one and only one Java object services HTTP requests.
Per-request
means that a
Java object is created to process each incoming request and is thrown away at the end of that
request. Per-request also implies statelessness, as no service state is held between requests.
For our example, we will write a
CustomerResource
class to implement our JAX-RS service
and assume it will be a singleton. In this example, we need
CustomerResource
to be a
singleton because it is going to hold state. It is going to keep a map of
Customer
objects in
memory that our remote clients can access. In a real system,
CustomerResource
would
probably interact with a database to retrieve and store customers and wouldn't need to hold
state between requests. In this database scenario, we could make
CustomerResource
per-re-
quest and thus stateless. Let's start by looking at the first few lines of our class to see how to
start writing a JAX-RS service:
package
package
com
.
restfully
.
shop
.
services
;
import
import
...
...
;
@Path
(
"/customers"
)
public
public class
class
CustomerResource
CustomerResource
{
private
private
Map
<
Integer
,
Customer
>
customerDB
=
new
new
ConcurrentHashMap
<
Integer
,
Customer
>();
private
private
AtomicInteger idCounter
=
new
new
AtomicInteger
();
As you can see,
CustomerResource
is a plain Java class and doesn't implement any particu-
lar JAX-RS interface. The
@javax.ws.rs.Path
annotation placed on the
CustomerRe-
source
class designates the class as a JAX-RS service. Java classes that you want to be re-
cognized as JAX-RS services must have this annotation. Also notice that the
@Path
annota-
tion has the value of
/customers
. This value represents the relative root URI of our custom-