在我的spring boot应用程序中,我想返回带有响应正文的不同类型的响应代码。
@RequestMapping(method = RequestMethod.POST, value = "/users")
public ResponseEntity<User> userSignsUp(@RequestBody User user) {
if(userService.getUserByNic(user.getNic()).equals(userService.getUserByNic(user.getNic()))) {
UserErrorBean userError = new UserErrorBean("User already exist","406 error");
return ResponseEntity<>(userError ,HttpStatus.CONFLICT); }
userService.userSave(user);
return ResponseEntity<>(user, HttpStatus.CREATED);
}
这是我的休息控制器,我想根据不同的条件返回不同的响应。但是,仅在满足用户NIC条件时返回条件。如果将用户添加到数据库,则会抛出NullPointerException()
。
我想根据请求返回响应。
答案 0 :(得分:0)
您可以像这样编写一个简单的RestController。
@PostMapping("/users")
public ResponseEntity<User> userSignsUp(@RequestBody User user) {
if(user == null){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if(userService.getUserByNic(user.getNic()).equals(userService.getUserByNic(user.getNic()))) {
UserErrorBean userError = new UserErrorBean("User already exist","406 error");
return new ResponseEntity<>(userError, HttpStatus.CONFLICT);
}
if(userService.userSave(user)) { // make it return boolean on success or failed
return new ResponseEntity<>(user, HttpStatus.CREATED);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}