How to request origin and body of a request in Spr

2019-03-04 00:22发布

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.

标签: java spring rest
3条回答
一纸荒年 Trace。
2楼-- · 2019-03-04 00:38

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.

查看更多
够拽才男人
3楼-- · 2019-03-04 00:45

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

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-04 00:55

Try this:

@RequestMapping(value = "/create", method = RequestMethod.POST)
public XXX createMyObject(HttpServletRequest request, @RequestBody String body) {
    String origin = URI.create(request.getRequestURL().toString()).getHost();
    System.out.println("Body: " + body + " Origin:" + origin);
    return XXX;
}
查看更多
登录 后发表回答