Spring Boot3 & Spring Framework 6 강의 ::Section.8 REST API HATEOAS 구현하기

suragryen·2024년 3월 14일
0

Udemy-Spring

목록 보기
22/25

  • 데이터를 반환하는것 뿐만 아니라 링크도 반환 할 수 있음!
  • 링크를 반환하여 사용자에게 후속작업을 수행할 수 있는 방법을 알려준다.
//Hateoas
	//EntityModel 도메인 객체를 랩핑하여 링크를 추가 
	//WebMvcLinkBuilder
	
	@GetMapping("/users/{id}")
	public EntityModel<User> retrieveUsers(@PathVariable int id){
	// EntityModel 클래스는 HATEOAS(Hypermedia as the Engine of Application State) 디자인 원칙을 따르는 RESTful API에서 사용
	//
		
		User user = service.findOne(id);
		
		if(user==null)
			throw new UserNotFoundException("id:" + id);
		
		EntityModel<User> entityModel = EntityModel.of(user);//특정 객체를 표현하고 이를 위한 링크를 포함하는데 사용
		WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers());
		entityModel.add(link.withRel("all-users"));//링크에 관계(rel)를 추가하여 클라이언트가 이 링크의 의미를 이해할 수 있도록 함. 
		//컨트롤러 메소드를 가리키는 링크를 생성. 
		// 링크 생성 및 관리를 쉽게 할 수 있도록 도와줌 
		
		return entityModel; 
	} 
	
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;

WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers());

import static 구문을 사용하면 특정 클래스의 정적 멤버들을 클래스 이름 없이 직접 사용할 수 있음 즉, 위의 코드에서 linkTo()나 methodOn()과 같은 정적 메서드를 클래스 이름 없이 직접 사용할 수 있습니다.(변수 없이 사용 가능)

all-users 의 링크

profile
블로그 이사중 ☃︎

0개의 댓글

관련 채용 정보