2

I would like to access multiple body parameters of different types to use in my POST route in my API, but I don't know how to access the body parameters in Javalin. I haven't found any information concerning body parameters or best POST practices in Javalin in the documentation. The closest thing I can find is this:

ctx.body()                // get body as string (consumes underlying request body if not cached)
ctx.bodyAsBytes()         // get body as bytes (consumes underlying request body if not cached)
ctx.bodyAsClass(class)    // get body as class (consumes underlying request body if not cached)
ctx.bodyValidator(class)  // get typed validator for body (consumes underlying body request if not cached)

Could somebody please point me in the right direction? Does Javalin even support body parameters?

mooglin
  • 500
  • 5
  • 17

1 Answers1

3

The basic ctx.body() method will give you access to the form data as a string:

fieldOne=valueOne&fieldTwo=valueTwo&...

This may be cumbersome to process - but there is also the option to read your form data directly into a bean: ctx.bodyAsClass(class). And if validation is needed, then you can use ctx.bodyValidator(class).

Alternatively, and perhaps more conveniently, you can use:

ctx.formParamMap()

This gives you a linked hash map of all your form data. You can iterate over all the submitted fields using this.

There are also related methods:

  • ctx.formParam(name) to return the String value for one field (using the form field's name)
  • ctx.formParams(name) to get a list of values if the field in question can have multiple values, like a multi-select dropdown list, or a set of related checkboxes for one form field, and so on.

If these do not help, then I think you may need to show us where exactly you are getting stuck, with some sample code.

andrewJames
  • 19,570
  • 8
  • 19
  • 51