Open In App

How to Use Spring @ResponseStatus to Set HTTP Status Code?

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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.

project metadata

Step 2: Add the Dependencies

Add the following dependencies into the Spring Boot project.

add the dependency

Step 3: Project Structure

Once created the project, the file structure looks like this:

project strcture

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.

output ui

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.

postman output ui


ResourceNotException raiser in application logs:

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