Reputation: 127
I would like to send datas (in json form) from frontend to backend using POST, but requestparameter is null.
Angular:
this.http.post('api/example', { mydata: JSON.stringify(data) },
{ "headers": { header: "text/html;charset=UTF-8" } }).subscribe(Response => console.log(Response);
});
JSON.stringify(data) looks like this:
[
["num1","num2","num3","num4","num5", "num6"],
["test6","test2","test1","test5","test4", "test3"]
]
This is just an example, the data will be dynamic, so sometimes I will have more or less columns and rows.
Spring backend:
@RequestMapping(value = "/api/example", method = RequestMethod.POST)
public @ResponseBody void postExample(HttpServletRequest request, HttpServletResponse response)
throws IOException {
HttpSession session = request.getSession();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
String mydata = request.getParameter("mydata");
System.out.println(mydata);
...
}
mydata is null, when I print out. I don't know why. What I tried:
I would like to use "getParameter" instead of using @RequestBody annotation.
How can I get the json data from frontend and use it in backend?
Edit: Originally I didn't want to use @RequestBody, but if I want to use it, how can I use it for getting these json arrays?
Upvotes: 0
Views: 592
Reputation: 2357
for using @RequestBody you'll need a Java data structure matching your JSON, e.g. a nested array
@PostMapping(path="/api/example")
public void postExample(@RequestBody ArrayList<ArrayList<String>> body) {
//....
}
Test case (from question above)
[
["num1","num2","num3","num4","num5", "num6"],
["test6","test2","test1","test5","test4", "test3"]
]
Upvotes: 1
Reputation: 1536
You need to use .getReader(), instead of the .getParameter() method, since you need to retrieve the body of the request not some parameter.
Upvotes: 1