2016-12-01 5 views
4

자동으로 REST 끝점을 만드는 여러 컨트롤러가 있습니다. 사용자 지정 컨트롤러에서 봄 REST 응답이 다릅니다.

@RepositoryRestResource(collectionResourceRel = "books", path = "books") 
public interface BooksRepository extends CrudRepository<Books, Integer> { 
    public Page<Books> findTopByNameOrderByFilenameDesc(String name); 
} 

내가 방문 할 때 : http://localhost:8080/Books

내가 다시 얻을 : 나는 내 자신의 컨트롤러를 만들 때

{ 
    "_embedded": { 
     "Books": [{ 
      "id": , 
      "filename": "Test123", 
      "name": "test123", 
      "_links": { 
       "self": { 
        "href": "http://localhost:8080/books/123" 
       }, 
       "Books": { 
        "href": "http://localhost:8080/books/123" 
       } 
      } 
     }] 
    }, 
    "_links": { 
     "self": { 
      "href": "http://localhost:8080/books" 
     }, 
     "profile": { 
      "href": "http://localhost:8080/profile/books" 
     }, 
     "search": { 
      "href": "http://localhost:8080/books/search" 
     }, 
     "page": { 
      "size": 20, 
      "totalElements": 81, 
      "totalPages": 5, 
      "number": 0 
     } 
    } 
} 

가 :

@Controller 
@RequestMapping(value = "/CustomBooks") 
public class CustomBooksController { 
    @Autowired 
    public CustomBookService customBookService; 

    @RequestMapping("/search") 
    @ResponseBody 
    public Page<Book> search(@RequestParam(value = "q", required = false) String query, 
           @PageableDefault(page = 0, size = 20) Pageable pageable) { 
     return customBookService.findAll(); 
    } 
} 

내가 다시 응답을 보이는 것 자동 생성 된 컨트롤러 응답과 같은 것 :

{ 
    "content": [{ 
     "filename": "Test123", 
     "name" : "test123" 
    }], 
    "totalPages": 5, 
    "totalElements": 81, 
    "size": 20, 
    "number": 0, 
} 

응답을 자동으로 생성 된 응답처럼 보이게하려면 어떻게해야합니까? 일관성있게 유지하고 싶기 때문에 다른 응답을 위해 코드를 다시 작성할 필요가 없습니다. 내가 다른 방식으로해야할까요?


편집 :이 찾았 Enable HAL serialization in Spring Boot for custom controller method

을하지만, 내가 수 있도록 내 REST 컨트롤러에서 변경해야하는 것을 이해하지 않습니다 PersistentEntityResourceAssembler. Google에서 PersistentEntityResourceAssembler을 검색했지만 예제가 없어도 유사한 페이지로 돌아갈 수 있습니다. (또는 예제가 나에게 적합하지 않은 것 같습니다.)

+1

'@ResourceRestContro 러너'? – chrylis

+0

귀하의 질문을 정확하게 이해하고 있는지 잘 모르겠지만 귀하가 찾고있는 것이 HATEOAS라고 생각됩니다. https://spring.io/guides/gs/rest-hateoas/ – Markus

+0

하나는 페이지를 반환합니다. s), 그러나 나는 그것이 오타이라고 생각한다? –

답변

5

@chrylis 제안에 따르면 주석을 @RepositoryRestController으로 바꿔 Spring-data-rest를 가져와 주어진 리소스를 맞춤 설정하기위한 ResourceProcessors를 호출해야합니다. 당신이 (당신의 스프링 데이터 나머지 BooksRepository 같은) HATEOAS 규격을 따르도록 자원에 대한

당신의 방법을 선언 반환 형식은 PagedResources에 Page 개체를 변환 HttpEntity<PagedResources<Resource<Books>>> 같아야합니다

  • 당신은 필요 이 객체를 autowire.

    @Autowired private PagedResourcesAssembler<Books> bookAssembler;

  • 이러한 변화는 당신이 org.springframework.hateoas.Resources을 얻을 포함 준수 반응을 도움이 될 것입니다

    return new ResponseEntity<>(bookAssembler.toResource(customBookService.findAll()), HttpStatus.OK);

처럼 return 문이 있어야 "_embedded""_links "속성을 사용했습니다.

+0

참고로이 답변을 사용할 수 있습니다 [link] http://stackoverflow.com/questions/31758862/enable-hal-serialization-in-spring-boot-for-custom-controller-method?noredirect=1&lq=1 –

+0

"@RestController"를 의미합니까? "@ResourceRestController"가 온라인에 표시되지 않습니다. "@Autowired"개인 PagedResourcesAssembler 을 추가하면 intelliJ는 자동 응답을 사용할 수 없다는 불평을합니다. 컴파일되고 springboot가 시작됩니다. 그러나 컨트롤러에 전화를 걸면 "예기치 않은 오류가 발생했습니다 (유형 = 내부 서버 오류, 상태 = 500). [PagedResource {content : [Resource {content : ....] 이 오류 페이지는 JSON이 아니라 XML로되어 있습니다. 내가 솔르에게서 뽑아 낸다는 건 중요하지 않아? 책이 제 모델입니다. –

+0

위의 기능을 사용하려면 CustomBooksController가 BooksRepository 클래스와 동일한 프로젝트에 있어야합니다. –