Home >Java >javaTutorial >When to use ResponseEntity?

When to use ResponseEntity?

Susan Sarandon
Susan SarandonOriginal
2025-01-10 08:44:41723browse

Quando usar ResponseEntity?

Let's look at the controller with the endpoint below:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    public ResponseEntity<String> get() {
        return ResponseEntity.ok("Hello World!");
    }
}

When using the @RestController annotation of Spring, by default the responses are placed in the body's of the responses, it is unnecessary to use ResponseEntity typing the method return, just the response type directly, as in the example below:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    public String get() {
        return "Hello World!";
    }
}

Also, by default, in case of success, the status code used in the endpoints is 200 (OK), that is, it is only necessary to change it when you want to use another status, and not ResponseEntity needs to be used, just use the annotation @ResponseStatus above method:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    @ResponseStatus(HttpStatus.ACCEPTED)
    public String get() {
        return "Hello World!";
    }
}

So why does ResponseEntity exist?

For cases where you need to add more information to the response than just the body and status, such as adding a header to response:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    public ResponseEntity<String> get() {
        return ResponseEntity.ok()
            .header("X-Test", "Blabla")
            .body("Hello World!");
    }
}

The above is the detailed content of When to use ResponseEntity?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn