O'Reilly logo

Java SOA Cookbook by Eben Hewitt

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

Working with Forms and URIs

Problem

You want an easy way to get data from an HTML form.

Solution

For each item in the form that you want to capture, use the @FormParam annotation within the method parameters.

Discussion

The form parameters annotation works like many other annotations in JAX-RS, such as @QueryParam and @PathParam—the values are injected by the runtime. So if you have either a short form with just a few input controls, or are only interested in a few values, it’s very easy to access form data using @FormParam.

Example 8-19 shows the code for the User entity that the form will create and that you’ll show in a static representation.

Example 8-19. User.java is the business entity the form creates

package com.soacookbook.rest.forms;

import java.util.Date;

/**
 * A business entity created by form input.
 */
public class User {

    private String id;
    private String name;
    private Date createdDate;

    //getters and setters omitted...
}

In a real-world application, you would use a database or some other persistent store to save created users. For the purposes of this example, you’ll just save them in a static map, as shown in Example 8-20.

Example 8-20. A mock database for saving users

package com.soacookbook.rest.forms;

import java.util.HashMap;
import java.util.Map;

/**
 * Mocks a database. When users are created by the form, they
 * are stored here for later retrieval.
 */
public class Database {
    static Map<String, User> users = new HashMap<String, User>();
}

The class that runs the show is the ...

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