스프링에서 HTTP의 상태 코드, 헤더, 바디 등을 유연하게 구성할 수 있음.
주로 컨트롤러에서 HTTP 응답을 만들 때 사용.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello, World!", HttpStatus.OK);
}
}
org.springframework.http.HttpStatus
주요 HttpStatus 상수
HttpStatus.OK (200 OK)
HttpStatus.CREATED (201 Created)
HttpStatus.ACCEPTED (202 Accepted)
HttpStatus.NO_CONTENT (204 No Content)
HttpStatus.BAD_REQUEST (400 Bad Request)
HttpStatus.UNAUTHORIZED (401 Unauthorized)
HttpStatus.FORBIDDEN (403 Forbidden)
HttpStatus.NOT_FOUND (404 Not Found)
HttpStatus.INTERNAL_SERVER_ERROR (500 Internal Server Error)
HttpStatus.BAD_GATEWAY (502 Bad Gateway)
HttpStatus.SERVICE_UNAVAILABLE (503 Service Unavailable)
숫자 형태와,
HttpStatusenum을 사용하는 방법이 있음. 그러나HttpStatusenum을 사용하는 것이 더 읽기 쉽고 유지보수하기 쉬운 코드를 작성하는데 도움이 됨.
return ResponseEntity.status(HttpStatus.OK).body("OK");
return ResponseEntity.ok().body("OK");
return ResponseEntity.ok("OK");
return ResponseEntity.status(400).body("Bad Request");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Bad Request");
return ResponseEntity.status(401).body("Unauthorized");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
return ResponseEntity.status(403).body("Forbidden");
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Forbidden");
return ResponseEntity.status(404).body("Not Found");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Not Found");
return ResponseEntity.status(500).body("Internal Server Error");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/resource")
public ResponseEntity<?> getResource() {
try {
// 리소스를 가져오는 로직
Object resource = someService.getResource();
return ResponseEntity.ok(resource);
} catch (ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
} catch (UnauthorizedException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized access");
} catch (BadRequestException ex) {
return ResponseEntity.badRequest().body("Bad request");
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An unexpected error occurred");
}
}
}