Sunday, September 3, 2023

How to return different HTTP status code from a Spring MVC controller? Example Tutorial

Hello guys, if you are wondering how to return different HTTP Status codes from a Spring MVC controller then you have come to the right place. You can use @ResponseCode annotation on Spring MVC to send different HTTP codes to the client as part of the HTTP response. If you are developing REST APIs then you can even @RestControler to do that job. This article will demonstrate how to return different HTTP statuses for a Spring MVC controller. Prior to implementation, all we need to understand what is with the HTTP return types and why we need them. Let's have a quick look into this.

As a developer, all you need to understand is that you must give a better experience to users of your system for better interaction. Letting other developers know, why the error happens in the code is a best practice that is used to develop well-organized software. 

Developers that use your service can work more efficiently because the chances of failure are reduced. This is where HTTP status codes come into play, along with a brief message in the body of the response that explains what's going on.

Before we go into an example, let's discuss the types of HTTP status codes. By the way, if you are new to Spring Framework itself and need resources to learn Spring in a guided manner then you can also check out I recommended best Spring Framework courses, and books to start with. 




What are common HTTP Codes for Web Developers?

Simply the HTTP code consists of 3 digits that come with the response of HTTP request. From the first digit of 3 digits, we can identify the type of response of HTTP requests. 

Informational (Starts with digit 1 ex- 1XX) - The request is received and the process is continuing. Alerts the sender to wait for the final response.

Successful (Starts with digit 2 ex- 2XX) - The request was successfully received and accepted.

Redirection ( Starts with 3 ex - 3XX) - The request was successfully received but needs to complete further action to complete the request.

Client Error (Starts with 4 ex - 4XX) - The client is the one who cause the error and needs to be fixed to send the request.

Server Error (Starts with 5 ex - 5XX) - The error was caused by the server.




Returning status code with @ResponseStatus  in Spring - Example

Spring Framework helps us out by providing an enum that contains all of the HTTP status codes. It's a flexible annotation that may be used in controllers at the class or method level, on Custom Exception Classes, and on @ControllerAdvice classes.

In this method, we use the @ResponseBody annotation in both cases. When used at the class level, all class methods will result in a response with the specified HTTP status code. All method which is annotated with the @ResponseStatus(code = HttpStatus.OK, reason = "OK") does not return an error code and only will return the 200 status code by default.

@Controller
@ResponseBody
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public class StudentController {

@GetMapping("/method")
@ResponseStatus(code = HttpStatus.OK, reason = "OK")
public String ok() {
return "Class Level HTTP Status Overridden. The HTTP Status will be OK (CODE 200)\n";
}

@GetMapping("/error")
public String serviceUnavailable() {
return "The HTTP Status will be SERVICE_UNAVAILABLE (CODE 503)\n";
}

}

As per this example, Spring Framework will respond with a 406 Code if it receives a GET request to "/method" URL.






Returning status code with an Exception

Now, let's see another example of a controller method to return HTTP status in case of an error or exception. To demonstrate this, we will add the second method to the controller to show how to use an exception to return a status code.

@RequestMapping(value = "/exception", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity sendViaException() {
throw new ForbiddenException();
}

If the GET request will come to the "/exception" URL path then it will throw a ForbiddenException and it will separate the class. 



That's all about how to return different HTTP status codes from a Spring MVC controller. This is an important concept which every Java developer should be familiar with. Just to recap, Spring Frameworks provides multiple ways to return custom status codes from its Controller classes like you can use a ResponseEntity@ResponseStatus annotation on exception classes, and by using the @ControllerAdvice and @ExceptionHandler annotations. So in this tutorial, we discussed the different HTTP statuses for a Spring MVC controller. See you in the next tutorial.

 Other Spring Framework articles you may like to explore 

    Thanks for reading this article so far. If you find this Spring MVC tutorial and HTTP status code example useful, please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.   

    No comments:

    Post a Comment