┝ framework/┎ Spring

@ResponseEntity

홍호나 2025. 5. 14. 13:35
public class ResponseEntity<T> extends HttpEntity<T>
Extension of HttpEntity that adds an HttpStatusCode status code. Used in RestTemplate as well as in @Controller methods.
HttpEntity의 확장이다. HttpStatusCode를 사용하여 status code를 받아올 수 있다. RestTemplate에 쓰이며 @Controller 메서드에서 사용된다.
In RestTemplate, this class is returned by getForEntity() and exchange():
RestTemplate에서 이 클래스는 getForEntity나 exchange 메서드에 의해 반환된다.
 ResponseEntity entity = template.getForEntity("https://example.com", String.class);
 String body = entity.getBody();
 MediaType contentType = entity.getHeaders().getContentType();
 HttpStatus statusCode = entity.getStatusCode();
 

This can also be used in Spring MVC as the return value from an @Controller method:

이것은 또한 Spring MVC에서 반환값으로 사용될 수 있다.

 @RequestMapping("/handle")
 public ResponseEntity<String> handle() {
   URI location = ...;
   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setLocation(location);
   responseHeaders.set("MyResponseHeader", "MyValue");
   return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
 }
 

 

Or, by using a builder accessible via static methods:

또는 builder를 사용하여 정적 메서드에 접근하게 할 수 있다.

 @RequestMapping("/handle")
 public ResponseEntity<String> handle() {
   URI location = ...;
   return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World");
 }