[RESTful Web Service]-3

EarlyBird·2021년 11월 1일
0

RESTful Web Service

목록 보기
3/6
post-thumbnail

Dowon Lee님의 Spring Boot를 이용한 RESTful Web Services 개발 강의를 학습한 내용입니다.

User Service API 구현

@Service
public class UserDaoService {
//...
}
  • @Service : Service 용도의 Bean
@RestController
public class UserController {

    private UserDaoService service;

    public UserController(UserDaoService service){
        this.service = service;
    } //생성자를 통한 의존성 주입
    //...
}
  • 생성자를 통한 의존성 주입

사용자 목록 조회 API

  • GET HTTP Method
    @GetMapping("/users")
    public List<User> retrieveAllUsers(){
        return service.findAll();
    }

    @GetMapping("/users/{id}")
    public User retrieveUser(@PathVariable int id){
        return service.findOne(id);
    }
  • @GetMapping("/users/{id}") : user 상세조회 => ex) users/10 -> Controller에는 String으로 전달됨 -> int로 선언하면 String값이 자동으로 변환되어 매핑됨

사용자 등록 API

  • POST HTTP Method
    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody User user){
        User savedUser = service.save(user);
        
        //URI 등록
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(savedUser.getId())
                .toUri();

        return ResponseEntity.created(location).build();
    }
  • @RequestBody : POST 메소드에서 사용, JSON 형식 데이터 추가
  • 201 Created

존재하지 않는 데이터 예외로 발생시키기

    @GetMapping("/users/{id}")
    public User retrieveUser(@PathVariable int id){
        User user = service.findOne(id);

        if(user == null){
            throw new UserNotFoundException(String.format("ID[%s] not found", id));
        }

        return user;
    }
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}
  • 404 Not Found
@RestControllerAdvice 
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request){
        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));

        return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
     @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);
    }
}
  • @RestControllerAdvice : @ResponseBody + @ControllerAdvice, @ControllerAdvice가 AOP를 적용해 컨트롤러 단에 적용
  • ResponseEntity : 사용자 추가 시 반환시킨 값
  • 404 Not Found : UserNotFound 일 때
  • 500 Internal Server Error : 이외의 예외
profile
안되면 되게 합시다

0개의 댓글