Home > Java > javaTutorial > When to use ResponseEntity?

When to use ResponseEntity?

Susan Sarandon
Release: 2025-01-10 08:44:41
Original
736 people have browsed it

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!");
    }
}
Copy after login

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!";
    }
}
Copy after login

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!";
    }
}
Copy after login

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!");
    }
}
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template