Web-service using spring in which I have to get the params from the body of my post request? The content of the body is like:-
source=”mysource”
&json=
{
"items": [
{
"username": "test1",
"allowed": true
},
{
"username": "test2",
"allowed": false
}
]
}
And the web-service method looks like:-
@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBody String a) throws MyException {
return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a),HttpStatus.OK);
}
Please let me know how do I get the params from the body? I can get the whole body in my string but I don't think that would be a valid approach. Please let me know how do I proceed further.
You will need these imports...
And, if you're using Maven, you'll also need this in the dependencies block of the pom.xml file in your project's base directory.
Then the above-listed fix by Jason will work:
In class do like this
In page do like this:
You can get param from request.
You can bind the json to a POJO using
MappingJacksonHttpMessageConverter
. Thus your controller signature can read :-Where RequestDTO needs to be a bean appropriately annotated to work with jackson serializing/deserializing. Your *-servlet.xml file should have the Jackson message converter registered in RequestMappingHandler as follows :-
You can try using @RequestBodyParam
https://github.com/LambdaExpression/RequestBodyParam
You can get entire post body into a POJO. Following is something similar
Where each field in Pojo (Including getter/setters) should match the Json request object that the controller receives..