Return standard HTTP status code in Spring Boot
This post will discuss how to return the standard HTTP status code in Spring Boot.
There are several ways to return HTTP status codes in Spring Boot, depending on the scenario and the level of control we want. Here are some of the possible solutions:
1. Using ResponseEntity Class
We can use the ResponseEntity class to wrap our response data and also specify the HTTP status code and headers. This gives us more flexibility and control over the response. For example, we can use the ResponseEntity.ok() method to create a response entity with a 200 (OK) status code and a JSON object as the body as follows:
|
1 2 3 4 5 6 7 8 |
@GetMapping(path = "/hello") public ResponseEntity<JSONObject> sayHello() { JSONObject jsonObject = new JSONObject(); jsonObject.put("status", true); jsonObject.put("message", "Data is found"); jsonObject.put("data", "Hello World"); return ResponseEntity.ok(jsonObject); } |
2. Using @ResponseStatus Annotation
We can use the @ResponseStatus annotation on our controller methods or exception classes to specify the HTTP status code that should be returned for that method or exception. For example, we can use the @ResponseStatus(HttpStatus.CREATED) annotation on a controller method that creates a new resource to indicate a 201 (Created) status code as follows:
|
1 2 3 4 5 6 |
@PostMapping(path = "/users") @ResponseStatus(HttpStatus.CREATED) public User createUser(@RequestBody User user) { // save user to db return userService.save(user); } |
3. Using @ControllerAdvice and @ExceptionHandler Annotations
We can use the @ControllerAdvice and @ExceptionHandler annotations to handle exceptions globally and return custom status codes based on the exception type. For example, we can create a class annotated with @ControllerAdvice that defines methods annotated with @ExceptionHandler for different exceptions and use the ResponseEntity class or the @ResponseStatus annotation to set the status code as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } @ExceptionHandler(DataIntegrityViolationException.class) @ResponseStatus(HttpStatus.CONFLICT) public void handleDataIntegrityViolation(DataIntegrityViolationException ex) { // Nothing to do } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleGenericException(Exception ex) { // Log the error } } |
That’s all about returning the standard HTTP status code in Spring Boot.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)