[Spring Boot] ServletUriComponentBuilder

이혜지·2022년 3월 28일
0

Spring

목록 보기
15/15

Rest Api를 구현하다가 ServletUriComponentBuilder를 이용하는 예제를 보고 적용하기 위해 정리하는 글

REST API를 구현하다 보면 사용자로 부터 요청이 왔을 때, 특정값을 포함한 uri를 전달해야하는 상황이 있다.
이때 사용하는 것이 ServletUriComponentBuilder이다.
ServletUriComponentBuilder를 통해 적절한 URI를 만들고 요청한 사용자에게 특정값을 포함한 URI를 전달 할 수 있다.

본 예제는 JpaRespository를 사용해서 save()메서드 후 추가된 사용자에 대한 id를반환해서 추가된 사용자 정보가 제대로 들어갔는지 확인하는 페이지로 이동할 URI를 만들어주기 위한 예제이다.
근데 이제 자바의 URIUriComponentBuilder를 곁들인,,,


@PostMapping("/signup")
	public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
    

		//새로운 유저를 생성하는 부분
		User user = new User(signUpRequest.getEmail(), signUpRequest.getPassword(), signUpRequest.getNickname(),
			signUpRequest.getDomain(), signUpRequest.getIntroduce());

		user.setPassword(passwordEncoder.encode(user.getPassword()));

		Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
			.orElseThrow(() -> new AppException("User Role not set."));

		user.setRoles(Collections.singleton(userRole));
        //대충 여기까지 유저 생성하는 부분
	
		User result = userRepository.save(user);
        //Jpa를 이용하여 유저를 save() 하는 부분 
        
        /**
      	컨텍스트 상대 경로 URI를 쉽게 만들게 해주는 UriComponentsBuilder를 컨트롤러 메서드의 인자로 지정
        */

		URI location = ServletUriComponentsBuilder
			.fromCurrentContextPath().path("/api/users/{user_id}")
			.buildAndExpand(result.getId()).toUri();
            
        /**
        UriComponentsBuilder와 User객체의 id로 리소스 URI를 만든다.
        path()메서드에 있는 {user_id}는 플레이스 홀더며, buildAndExpand() 메서드에 넘겨준 값으로 치환된다.
        */

		return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
        
        /**
        HTTP 응답 헤더를 설정하려면 메서드에서 User객체가 아닌 ResponseEntity객체를 반환해야한다. ResponseEntity객체에는 응답 헤더인 HttpHeaders객체, 상태 코드인 HttpStatus를 설정한다.
        */
	}

참고: static ResponseEntity.BodyBuilder의 created(URI location)
-> Create a new builder with a CREATED status and a location header set to the given URI(CREATED 상태와 위치 헤더가 지정된 URI로 설정된 새 빌더를 작성하십시오.)

결과 화면

localhost:8080/api/users로 POST 요청을 보내 user를 생성하면,
Header로 넘어오는 location을 확인 할 수 있다.

profile
공유 문화를 지향하는 개발자입니다.

0개의 댓글