Reputation: 23
I have a Spring Boot application and this handler method:
@PostMapping("/{id}")
public User create(@PathVariable("id") Long id, @RequestBody User user) {
if (id > 0 && id < 10) {
String fullName = user.getFirstName() + " " + user.getLastName();
user.setId(id);
user.setFullName(fullName);
} else {
//Return 401 ?
}
return userService.save(user);
}
How can I return return 401?
The response JSON should look like:
{
"msg": "empty",
"status" : "401"
}
Upvotes: 2
Views: 2109
Reputation: 2363
You can do it, using ResponseEntity
.
You would need to change your method return type to ResponseEntity<?>
, and change your method body to:
if (id > 0 && id < 10) {
String fullName = user.getFirstName() + " " + user.getLastName();
user.setId(id);
user.setFullName(fullName);
return new ResponseEntity<>(userService.save(user), HttpStatus.OK);
}
return new ResponseEntity<>(yourJsonObject, HttpStatus.UNAUTHORIZED);
Java Spring rest return unauthorized json
Upvotes: 3