formFieldMap
Signature¶
def formFieldMap: Directive1[Map[String, String]]
Description¶
Extracts all HTTP form fields at once as a Map[String, String]
mapping form field names to form field values. Data posted from HTML Forms is either of type application/x-www-form-urlencoded
or of type multipart/form-data
.
If form data contain a field value several times, the map will contain the last one.
See formFields for an in-depth description.
Warning¶
Use of this directive can result in performance degradation or even in OutOfMemoryError
s. See formFieldSeq for details.
Example¶
sourceval route =
formFieldMap { fields =>
def formFieldString(formField: (String, String)): String =
s"""${formField._1} = '${formField._2}'"""
complete(s"The form fields are ${fields.map(formFieldString).mkString(", ")}")
}
// tests:
Post("/", FormData("color" -> "blue", "count" -> "42")) ~> route ~> check {
responseAs[String] shouldEqual "The form fields are color = 'blue', count = '42'"
}
Post("/", FormData("x" -> "1", "x" -> "5")) ~> route ~> check {
responseAs[String] shouldEqual "The form fields are x = '5'"
}
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.formFieldMap;
final Function<Map<String, String>, String> mapToString =
map ->
map.entrySet().stream()
.map(e -> e.getKey() + " = '" + e.getValue() + "'")
.collect(Collectors.joining(", "));
final Route route =
formFieldMap(fields -> complete("The form fields are " + mapToString.apply(fields)));
// tests:
final FormData formDataDiffKey =
FormData.create(Pair.create("color", "blue"), Pair.create("count", "42"));
testRoute(route)
.run(HttpRequest.POST("/").withEntity(formDataDiffKey.toEntity()))
.assertEntity("The form fields are color = 'blue', count = '42'");
final FormData formDataSameKey = FormData.create(Pair.create("x", "1"), Pair.create("x", "5"));
testRoute(route)
.run(HttpRequest.POST("/").withEntity(formDataSameKey.toEntity()))
.assertEntity("The form fields are x = '5'");
1.0.1