httpStatus sprintboot
- User
httpStatus sprintboot
- Assistant
HttpStatus is an enum class in Spring Boot that encapsulates all HTTP status codes. It provides a set of pre-defined constants for representing different HTTP status codes such as 200 OK, 404 Not Found, 500 Internal Server Error, etc. HttpStatus can be used to set the HTTP status code of a response in an HTTP request-response cycle.
For example, suppose you want to return a response with a status code of 404 Not Found. In that case, you can use the following code snippet:
javaimport org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { // custom exception class } - User
HttpStatus 重構
- Assistant
HttpStatus是Spring Boot中枚舉類,封裝了所有HTTP狀態碼。它提供了一組預定義的常量,用於表示不同的HTTP狀態碼,例如200 OK、404 Not Found、500 Internal Server Error等。
有時候,我們需要根據不同的情況返回不同的HTTP狀態碼,此時,可以根據情況重構HttpStatus。
例如,假設我們編寫了一個Controller,其中一個方法處理添加用戶的請求,如果添加成功,返回201 Created,否則返回400 Bad Request。
最初的代碼如下:
java@PostMapping("/users") public ResponseEntity<User> addUser(@RequestBody User user) { User addedUser = userService.addUser(user); if(addedUser == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(addedUser, HttpStatus.CREATED); }我們可以使用HttpStatus的不同常量來重構它。首先,我們可以將HttpStatus.BAD_REQUEST提取出來,命名為BAD_REQUEST_CODE,使代碼更加可讀:
java