Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to request origin and body of a request in Spring controller

Tags:

java

rest

spring

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.

like image 688
Ayane Avatar asked Dec 07 '22 15:12

Ayane


2 Answers

To answer your questions:

  1. If you include HttpServletRequest in your method parameters you will be able to get the origin information from there. eg.

    public XXX createMyObject(@Requestbody String data, HttpServletRequest request) {
            String origin = request.getHeader(HttpHeaders.ORIGIN);
            //rest of code...
    

    }

  2. 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);

like image 132
craigwor Avatar answered Apr 05 '23 23:04

craigwor


You should be able to get headers and uris from HttpServletRequest object

public XXX createMyObject(@RequestBody String data, HttpServletRequest request)

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.

like image 21
J.Doe Avatar answered Apr 06 '23 00:04

J.Doe