![](/img/trans.png)
[英]Java/Spring > Handle Bad Request response for controller method with @RequestBody when no body is sent in request
[英]Handle two kinds of request body in controller - java
对于 post 方法,我有一个这样的请求正文。
{
"emp_id" : "1234"
}
Controller是这样的。
@PostMapping("/employees)
public ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody HashMap<String,String> params){
}
现在我的请求正文将更新为如下所示。
{
"emp_id" : "1234",
"ids" : ["4567","9087"]
}
如何更新 controller 中的帖子映射? 有人可以帮忙吗?
如果使用 POJO 从请求体中获取值,会更容易处理
public RequestData{
private String emp_id;
private List<String> ids;
...
//TODO: getters and setters here
}
然后在 controller 中:
@PostMapping("/employees)
public ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody RequestData requestData){
}
这样,如果请求中没有包含某个字段,它将 map 变为 null。
您可以使用 Map<String, Object> 中的参数
下面是示例结果。
@PostMapping("/employees)
public ResponseEntity<EmployeeResponse> getMatchingValues(@RequestBody HashMap<String,Object> params){
System.out.println("params = "+params);
}
Output 是:params = {emp_id=1234, ids=[4567, 9087]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.