User ๋๋ฉ์ธ ํด๋์ค ์์ฑ
๋๋ฉ์ธ
ํน์ ์ ๋ฌธ ๋ถ์ผ์์ ์ฌ์ฉ๋๋ ์ ๋ฌธ ์ง์
์คํ ๋ ์คํ์
ํด๋น ํด๋์ค๊ฐ ์ด๋ ์ฉ๋๋ก ์ฌ์ฉ๋ ๊ฒ์ธ์ง ๋ํ๋ด๋ ๊ฒ → ์์กด์ฑ ์ฃผ์ ์ ๋์๋๋ค.
ex) @RestController, @Service
POST
@RequestBody ๋ฅผ ์ ์ธํด ํ์ฌ variable์ด requestbody ํ์์ผ๋ก ๋ค์ด์จ๋ค๋ ๊ฒ์ ์๋ฆผ
HTTP Status Code
- 2XX → OK
- 4XX → Client
- 5XX → Server
@ServletUriComponentsBuilder๋ฅผ ์ด์ฉํด ํธ์ถ ๋ฐฉ๋ฒ์ ๋ฐ๋ผ ์ ์ ํ status code๋ฅผ ๋ฐํํจ
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user){
User savedUser = service.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
Exception Handling
[Controller]
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
User user = service.findOne(id);
if (user == null){
throw new UserNotFoundException(String.format("ID[%s] is not found", id));
}
return user;
}
[Exception]
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
AOP ์ฌ์ฉ(Aspect Oriented Programming)
์คํ๋ง ๋ถํธ ์ดํ๋ฆฌ์ผ์ด์ ๋ด์์ ๊ณตํต์ ์ผ๋ก ์ฒ๋ฆฌ๋์ด์ผ ํ๋ ๋ก์ง์ด๋ ๋ฉ์๋ ์ถ๊ฐ
Aspect๋ก ๋ชจ๋ํํ๊ณ ํต์ฌ์ ์ธ ๋น์ฆ๋์ค ๋ก์ง์์ ๋ถ๋ฆฌํ์ฌ ์ฌ์ฌ์ฉ
- @ControllerAdvice
- ๋ชจ๋ Controller๊ฐ ์คํ๋ ๋ annotation์ ๊ฐ์ง๊ณ ์๋ bean์ด ํญ์ ๋จผ์ ์คํ๋จ
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
}
'๐ฟ Spring > โ RESTful Web Service' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
5. Java Persistence API ์ฌ์ฉ (0) | 2023.06.20 |
---|---|
4. Spring Boot API ์ฌ์ฉ (0) | 2023.06.20 |
3. RESTful Service ๊ธฐ๋ฅ ํ์ฅ (0) | 2023.06.20 |
1. Spring Boot๋ก ๊ฐ๋ฐํ๋ RESTful Service (0) | 2023.06.20 |
0. Web Service & Web Application (0) | 2023.06.20 |
๋๊ธ