Reputation: 462
I'd like to be able to get the parameters passed to the POST request dynamically in runtime, like it can be done with GET.
The parameters I need are defined by one of the parameters passed, I can't know what they are before I read it.
Example:
If I pass to a request the param "type=player", I can deduce that the other params passed to this request are "id" and "name", but I can't know it until I read the "type" param.
In another case, the param "type=item" might be passed, and then I can deduce that the other params passed are "quantity" and "quality".
When I use GET, I can use request.getParameter("type") and afterwards understand what other params I'm looking for (request is HttpServletRequest). e.g. do something like:
if (request.getParameter("type") == "player") {
doSomething(request.getParameter("id"), request.getParameter("name"))
}
else if (request.getParameter("type") == "item") {
doSomethingElse(request.getParameter("quantity"), request.getParameter("quality"))
}
However when I use POST, from what I read so far I must define what parameters I'm expecting to be passed beforehand.
For instance, if the POST consumes JSON, I'll have to specify in the constructor a compiled Java object into which the JSON will be parsed once a request is made.
Since the Java object is defined at compile time, I have no way to dynamically accept and deduce different parameters.
Is there a way to dynamically access parameters passed to POST the same way it can be done with GET?
Upvotes: 1
Views: 1457
Reputation: 1851
It's easy to get the full body, just by doing this:
@POST
public Response go(String requestBody) throws IOException {
//parse the variable requestBody to get the parameters...
}
The value of the String variable requestBody
contains all the POST body.
However to facilitate your life Jersey offers:
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String, String> formParams) {
// Store the message
}
The keys of in the Map formParams
are your form POST parameters.
Upvotes: 2