Mastering Spring’s ResponseEntity: Custom Status, Headers, and File Downloads

This article explains why Spring Boot developers should return a ResponseEntity instead of a plain business object, covering its structure, custom status codes, headers, body handling, and a practical example of serving file downloads with proper content disposition.

Programmer DD
Programmer DD
Programmer DD
Mastering Spring’s ResponseEntity: Custom Status, Headers, and File Downloads

ResponseEntity

ResponseEntity

is Spring's wrapper for HTTP responses. It extends HttpEntity and contains three parts: the HTTP status code ( HttpStatus), response headers, and the response body. For simple data retrieval you can return the entity directly with @RestController:

@GetMapping("/user")
public User userinfo() {
    User user = new User();
    user.setUsername("felord.cn");
    return user;
}

Returning a ResponseEntity gives you more flexibility:

@GetMapping("/userinfo")
public ResponseEntity<User> user() {
    User user = new User();
    user.setUsername("felord.cn");
    return ResponseEntity.ok(user);
}

Custom Status Codes

While ResponseEntity.ok() returns HTTP 200, you can set any status with ResponseEntity.status(HttpStatus|int).

Custom Response Body

Use .body(Object) to specify the response payload:

ResponseEntity.status(HttpStatus.OK)
    .body(Object)

Response Headers

Standard headers have dedicated methods, and you can add custom ones with header(String name, String... values):

ResponseEntity.status(HttpStatus.OK)
    .allow(HttpMethod.GET)
    .contentType(MediaType.APPLICATION_JSON)
    .contentLength(1048576)
    .header("My-Header", "felord.cn")
    .build();

Underlying Mechanism

Spring MVC uses HandlerMethodReturnValueHandler to process controller return values. The implementation HttpEntityMethodProcessor handles HttpEntity (and thus ResponseEntity) and delegates the three pieces of information to ServletServerHttpResponse for rendering.

Practical Use: File Download

Instead of manually writing to HttpServletResponse, you can return a ResponseEntity<Resource>:

@GetMapping("/download")
public ResponseEntity<Resource> load() {
    ClassPathResource classPathResource = new ClassPathResource("application.yml");
    String filename = classPathResource.getFilename();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentDisposition(ContentDisposition.inline().filename(filename, StandardCharsets.UTF_8).build());
    return ResponseEntity.ok()
            .headers(httpHeaders)
            .body(classPathResource);
}

The process involves three steps:

Wrap the file to be downloaded as a org.springframework.core.io.Resource implementation (e.g., ClassPathResource, InputStreamResource, PathResource).

Configure the Content‑Disposition header. inline displays the file in the browser, while attachment forces a download. Also set the correct Content‑Type based on the file extension if needed.

Assemble and return ResponseEntity<Resource>.

See org.springframework.http.converter.ResourceHttpMessageConverter for the underlying implementation details.

In summary, ResponseEntity provides a powerful way to control HTTP status, headers, and body in Spring applications, and it simplifies tasks such as file downloads. The open‑source Payment Spring Boot library makes extensive use of this pattern.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaSpring BootHTTPFile DownloadResponseEntity
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.