Request Values: FormFields
Loading

Request Values: FormFields

A collection of pre-defined Request values that can be used to extract header values from incoming requests.

Description

FormField request values allow extracting fields submitted as application/x-www-form-urlencoded values or concrete instances from HTTP requests.

The FormField request value builder is made up of 2 steps, initially you need to pick which what type of value you want to extract from the field (for example intValue, which would reject the route if the value is not an int), and then optionally you may specify if the value is optional (by calling optional() on the RequestVal) or has a default value (by calling withDefault() on the RequestVal).

Examples

Extracting form fields of a certain primitive type from a request:

FormField<String> name = FormFields.stringValue("name");
FormField<Integer> age = FormFields.intValue("age");

final Route route =
  route(
    handleWith2(name, age, (ctx, n, a) ->
      ctx.complete(String.format("Name: %s, age: %d", n, a))
    )
  );

// tests:
final FormData formData = FormData.create(
  Pair.create("name", "Blippy"),
  Pair.create("age", "42"));
final HttpRequest request =
  HttpRequest
    .POST("/")
    .withEntity(formData.toEntity());
testRoute(route).run(request).assertEntity("Name: Blippy, age: 42");

Extracting values of custom type from a request by providing a conversion function:

FormField<SampleId> sampleId = FormFields.fromString("id", SampleId.class, s -> new SampleId(Integer.valueOf(s)));

final Route route =
  route(
    handleWith1(sampleId, (ctx, sid) ->
      ctx.complete(String.format("SampleId: %s", sid.id))
    )
  );

// tests:
final FormData formData = FormData.create(Pair.create("id", "1337"));
final HttpRequest request =
  HttpRequest
    .POST("/")
    .withEntity(formData.toEntity());
testRoute(route).run(request).assertEntity("SampleId: 1337");

Contents