Java Reference
In-Depth Information
src/main/java/com/restfully/shop/CustomerResource.java
@Path
(
"/customers"
)
public
public class
class
CustomerResource
CustomerResource
{
...
@POST
@Produces
(
"text/html"
)
public
public
Response
createCustomer
(
@FormParam
(
"firstname"
)
String first
,
@FormParam
(
"lastname"
)
String last
)
{
The HTML form posts data to the
createCustomer()
method of
CustomerResource
when
users click the Send button:
Customer customer
=
new
new
Customer
();
customer
.
setId
(
idCounter
.
incrementAndGet
());
customer
.
setFirstName
(
first
);
customer
.
setLastName
(
last
);
customerDB
.
put
(
customer
.
getId
(),
customer
);
System
.
out
.
println
(
"Created customer "
+
customer
.
getId
());
String output
=
"Created customer <a href=\"customers/"
+
customer
.
getId
() +
"\">"
+
customer
.
getId
()
+
"</a>"
;
String lastVisit
=
DateFormat
.
getDateTimeInstance
(
DateFormat
.
SHORT
,
DateFormat
.
LONG
).
format
(
new
new
Date
());
return
return
Response
.
created
(
URI
.
create
(
"/customers/"
+
customer
.
getId
()))
.
entity
(
output
)
.
cookie
(
new
new
NewCookie
(
"last-visit"
,
lastVisit
))
.
build
();
}
The
createCustomer()
method does a couple things. First, it uses the form data injected
with
@FormParam
to create a
Customer
object and insert it into an in-memory map. It then
builds an HTML response that shows text linking to the new customer. Finally, it sets a cook-
ie on the client by calling the
ResponseBuilder.cookie()
method. This cookie, named
last-visit
, holds the current time and date. This cookie will be used so that on subsequent
requests, the server knows the last time the client accessed the website:
@GET
@Path
(
"{id}"
)
@Produces
(
"text/plain"
)
public
public
Response
getCustomer
(
@PathParam
(
"id"
)
int
int
id
,