O'Reilly logo

RESTful Java with JAX-RS by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required