Getting Post parameters in a ResponseBody using Java Spring
Getting Post parameters in a ResponseBody using Java Spring
I am having an issue getting my post parameters to show up in my Spring Controller. When I try with the below code I get the following output
JQuery
$table.DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": './go/Reports/datatablesJson/',
"type": "POST",
"data": function(data){
console.log(JSON.stringify(options));
return JSON.stringify(options);
},
"contentType": "application/json;charset=UTF-8"
},
"columns": columns
});
Spring Controller:
@RequestMapping(value = "/datatablesJson", method = RequestMethod.POST)
@ResponseBody
public String datatablesJson(HttpServletRequest request, @RequestBody ReportParams params) {
String reportData;
LOGGER.info("From RequestBody", params);
checkResponses(request);
switch ("params.reportType") {
case "training":
reportData = TrainingReport.initialize();
break;
default:
LOGGER.error("Invalid graph type");
return "errors/error";
}
return reportData;
}
Check Responses: Used to check the ServletRequest for my data
private void checkResponses(HttpServletRequest request) {
try {
BufferedReader reader = request.getReader();
String str = new String();
String data = new String();
while ((str = reader.readLine()) != null) {
data = data.concat(str);
}
HashMap<String, Object> responses = new ObjectMapper().readValue(data, HashMap.class);
LOGGER.info("From the ServletRequest", responses);
} catch (IOException ex) {
}
}
ReportParams: POJO with attributes mapping to params being passed up
public class ReportParams{
private String reportType;
private String empId;
private String level;
getters and setters for each attribute
}
---OUTPUT---
Chrome Console: {"reportType": "training", "empId": "9999", "level": "top"} - Valid Json according to Json Lint
Output from Server:
From RequestBody: reportType: null, empId: null, level: null
From ServletRequest: {reportType=training, empId=9999, level=top}
Why is my RequestBody cast failing when I can clearly see the data in the ServletRequest? And how do I fix it?
Thank you in advanced for any guidance.
Answers
I wound up finding a temporary solution based on what I already have using reflection. But I still feel like this shouldn't be necessary.
This question seems more specific to your Spring Controller and not necessarily a Datatables issue. Someone on the forum may be familiar and will answer your question but you may get a better/faster response on a forum geared towards the Spring Controller.
Kevin