[英]How to request origin and body of a request in Spring controller
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,我正在使用 Java 和 Spring 构建一个 REST API,我需要在我的控制器中处理一个 POST 请求,但我需要从该请求中提取主体,它是一个 JSON,也是该请求的“来源”,
@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?.我有几个问题:首先是如何获取该请求的来源(我猜这是一个在标头中传输的 url?),是否有与 @RequestBody 类似的注释?
My second question is what is usually the proper object to return in these kind of post methods as a response.我的第二个问题是在这些 post 方法中作为响应返回的正确对象通常是什么。
To answer your questions:回答您的问题:
If you include HttpServletRequest
in your method parameters you will be able to get the origin information from there.如果您在方法参数中包含
HttpServletRequest
,您将能够从那里获取源信息。 eg.例如。
public XXX createMyObject(@Requestbody String data, HttpServletRequest request) { String origin = request.getHeader(HttpHeaders.ORIGIN); //rest of code...
} }
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.对于休息响应,您需要返回对象 (json) 或 HttpStatus 的表示,以通知客户端调用是否成功。 eg
Return ResponseEntity<>(HttpStatus.ok);
例如
Return ResponseEntity<>(HttpStatus.ok);
You should be able to get headers and uris from HttpServletRequest object您应该能够从 HttpServletRequest 对象中获取标头和 uri
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.至于响应,我会说返回字符串,它是一个视图名称,您可以向它传递一些属性,说明操作成功与否,或 ModelAndView。
@Autowired private HttpServletRequest servletRequest; @Autowired 私有 HttpServletRequest servletRequest;
You can declare request object and then access in method to get Uri您可以声明请求对象,然后在方法中访问以获取 Uri
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.