I'm building a REST API using Java and Spring and I need to handle a POST request in my controller, but I need to extract the body from that request which is a JSON and also the "origin" of that request,
@RequestMapping(value = "/create", method = RequestMethod.POST)
public XXX createMyObject(@RequestBody String data, YYY){
MyObject mo = new MyObject();
mo.setData = data;
mo.setOrigin = yyy;
myRepository.save(mo);
return XXX;
}
I have a few questions: First is how can I obtain the origin of that request( which I guess is an url that travels in the header?), is there a similar annotation as the @RequestBody for that?.
My second question is what is usually the proper object to return in these kind of post methods as a response.
You should be able to get headers and uris from HttpServletRequest object
As for response I'd say return String which would be a view name to which you can pass some attributes saying that operation was successful or not, or ModelAndView.
To answer your questions:
If you include
HttpServletRequest
in your method parameters you will be able to get the origin information from there. eg.}
For rest responses you will need to return a representation of the object (json) or the HttpStatus to notify the clients whether the call wass successful or not. eg
Return ResponseEntity<>(HttpStatus.ok);
Try this: