How to Use Spring @ResponseStatus to Set HTTP Status Code?
Last Updated :
22 Aug, 2024
In a Spring Boot application, handling HTTP responses with the appropriate status code is crucial for communicating the outcome of a request to the client. The @ResponseStatus annotation in Spring allows developers to set the HTTP status code directly from a controller or exception handler. This approach simplifies error handling and response management, enabling a more declarative style without the need to manually set the status code in each response.
Using Spring @ResponseStatus to Set HTTP Status Code
The @ResponseStatus annotation can be applied to either a method or an exception class. When applied to a method, it sets the HTTP status code for the response returned by that method. When applied to an exception class, it sets the status code that will be returned when that exception is thrown.
How the @ResponseStatus annotation works:
- Value: This attribute sets the HTTP status code such as the HttpStatus.OK, HttpStatus.NOT_FOUND, etc.
- Reason (Optional): This attribute sets the custom reason phrase that is sent back to the client in the response.
Example:
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found")
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
In this example, when the ResourceNotFoundException is thrown then the response will have 404 Not Found status code with the reason "Resource not found".
Implementation of @ResponseStatus to Set HTTP Status Code
Step 1: Create a new Spring Boot Project
Create a new Spring Boot Project using IntelliJ Idea. Choose the below options:
- Name: spring-responseStatus-demo
- Language: Java
- Type: Maven
- Packaging: Jar
Click the Next button.
Step 2: Add the Dependencies
Add the following dependencies into the Spring Boot project.
Step 3: Project Structure
Once created the project, the file structure looks like this:
Step 4: Create the Custom Exception
Create the custom exception class to represents the resource not found scenario.
Java
package com.gfg.springresponsestatusdemo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found")
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
Using the @ResponseStatus annotation to set the status code to 404 not Found whenever this exception is thrown of the application.
Step 5: Create the REST Controller
Create the REST controller with the endpoint that throws the custom exception if a resource is not found.
Java
package com.gfg.springresponsestatusdemo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ResourceController {
@GetMapping("/resource/{id}")
public String getResource(@PathVariable("id") int id) {
if (id != 1) {
throw new ResourceNotFoundException("Resource with ID " + id + " not found.");
}
return "Resource found";
}
}
getResource method checks if the requested resource exists. If the resource does not exists then the ResourceNotFoundException is thrown which sets the response status 404 not Found.
Step 6: Main class
No changes are required in the main class.
Java
package com.gfg.springresponsestatusdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ResponseStatusApplication {
public static void main(String[] args) {
SpringApplication.run(ResponseStatusApplication.class, args);
}
}
pom.xml file:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>spring-responseStatus-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-responseStatus-demo</name>
<description>spring-responseStatus-demo</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 7: Run the application
Once completed the project, it will run and start at port 8080.
Step 8: Test the Endpoint
We can try to accessing the endpoint with the non-existing resource ID.
http://localhost:8080/resource/2
We should recieve the 404 Not Found status with the message "Resource not found" of the Spring Boot project.
ResourceNotException raiser in application logs:
This example project demonstrates how the @ResponseStatus annotation can effectively manage the HTTP status codes in the Spring Boot application.
Similar Reads
How to Use Spring ResponseEntity to Manipulate the HTTP Response? ResponseEntity is a powerful class in the Spring Framework that provides a flexible way to handle HTTP responses. It allows us to customize the HTTP response, including the status code, headers, and body, giving you complete control over what is sent back to the client. This class is particularly us
4 min read
How to send HTTP response code in PHP? HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version. For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-cas
2 min read
How to Get a Response Body When Testing the Status Code in WebFlux WebClient? Spring WebFlux is an HTTP request client. Reactor is the foundation of WebClient's functional and fluid API, allowing declarative building of asynchronous logic without requiring knowledge of threads or concurrency. It uses the same codecs that are also used to encode and decode request and response
4 min read
How to get Response Status Code with Selenium WebDriver? In web automation and testing, obtaining the HTTP response status code is crucial for validating the accessibility and health of web pages. While Selenium WebDriver is widely recognized for its powerful capabilities in automating browser interactions, it does not directly provide methods for fetchin
4 min read
What do you understand by the HTTP Status Codes ? The HTTP or the HyperText Transfer Protocol is a protocol of the application layer. It helps in establishing communication between a web browser and a web server. When a client requests any information, the browser sends a response using numeric status codes. These status codes are in the form of 3-
3 min read
Spring @ResponseStatus Annotation The @ResponseStatus annotation in Spring is the powerful tool used in the building RESTful web services. It is allowed developers to control HTTP (Hypertext Transfer Protocol) status code returned by the application's endpoints or when specific exceptions are thrown. By annotating methods or excepti
4 min read