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

15,236

Solution 1

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

Solution 2

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.

Share:
15,236

Related videos on Youtube

Ayane
Author by

Ayane

Updated on May 30, 2022

Comments

  • Ayane
    Ayane almost 2 years

    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.

  • Snackoverflow
    Snackoverflow almost 4 years
    Isn't the request URL a bit different from the HTTP origin header? One should be the source address of the request, the other one the website domain which initiates the request?
  • membersound
    membersound over 3 years
    You can even use HttpHeaders.ORIGIN constant.
  • Hikaru Shindo
    Hikaru Shindo about 2 years
    I always get NULL