You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.
O'Reilly logo

Example ex05_2: Forms and Cookies

The ex05_2 exercise shows examples of injecting form data, cookies, and HTTP headers using the @FormParam, @CookieParam, and @HeaderParam annotations. This example is a bit different than former examples, as there is no client code. Instead, to see these annotations in action, you will use a browser as your client.

The Server Code

The example starts off with an HTML form defined in src/main/webapp/index.html:

<html>
<body>

<form action="/rest/customers" method="post">
    First Name: <input type="text" name="firstname"/><br/>
    Last Name: <input type="text" name="lastname"/><br/>
    <INPUT type="submit" value="Send">
</form>

</body>
</html>

It is a simple form for creating a customer using our familiar CustomerResource service:

src/main/java/com/restfully/shop/CustomerResource.java

@Path("/customers")
public class CustomerResource {
...
   @POST
   @Produces("text/html")
   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 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( ...

The best content for your career. Discover unlimited learning on demand for around $1/day.