Как получить содержимое страницы в Spring Rest Client - PullRequest
0 голосов
/ 03 мая 2018

У меня есть следующий REST-контроллер:

@RestController
class PersonController {

   final PersonService personService

   @Autowired
   PersonController( PersonService personService ){
    this.personService = personService
   }

   @RequestMapping(value="/persons",method=RequestMethod.GET)
   Page<Person> list( Pageable pageable){
     Page<Person> persons = personService.listAllByPage(pageable)
     persons
   } 
}

Следующий репозиторий:

interface PersonRepository extends PagingAndSortingRepository<Person,Integer> {

}

И услуга:

interface PersonService {
   Page<Person> listAllByPage(Pageable pageable)
}

@Service
class PersonServiceImpl implements PersonService {

   final PersonRepository personRepository

   @Autowired
   PersonServiceImpl(PersonRepository personRepository){
      this.personRepository = personRepository
   }

   @Override
   Page<Person> listAllByPage(Pageable pageable) {
       personRepository.findAll(pageable)
   } 
}

Сервер работает как положено, но у меня проблема с клиентом. Я не знаю, как получить содержание из ответа.

В клиенте у меня есть такой метод:

@Override
public List<PersonDTO> findAll() throws DataAccessException {
    try {
        restClient.getServiceURI(PERSON_URL));
        ResponseEntity<PageImpl<PersonDTO>> response =
            restClient.exchange(
                restClient.getServiceURI(PERSON_URL),
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<PageImpl<PersonDTO>>() {
                });
        return response.getBody().getContent();
    } catch (Exception e){}
}

Но я получаю следующее исключение:

 org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.data.domain.PageImpl]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.PageImpl` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

Теперь я читаю эту запись stackoverflow и добавляю класс CustomPageImpl: Как использовать ответ страницы с использованием Spring RestTemplate

Я изменяю метод в клиенте на следующий:

@Override
public List<PersonDTO> findAll() throws DataAccessException {
    try {
        restClient.getServiceURI(PERSON_URL));
        ResponseEntity<CustomPageImpl<PersonDTO>> response =
            restClient.exchange(
                restClient.getServiceURI(PERSON_URL),
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<CustomPageImpl<PersonDTO>>() {
                });
        return response.getBody().getContent();
    } catch (Exception e){}
}

Но теперь я получаю почти то же исключение:

 org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.data.domain.Pageable]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Pageable` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

1 Ответ

0 голосов
/ 03 мая 2018

В той же записи о переполнении стека, о которой вы упоминали, есть решение для запроса на обмен. Вы можете использовать PagedResources вместо реализации Page / Custom. Для получения более подробной информации см. Ссылку .

Здесь будет ваш запрос: -

ResponseEntity<PagedResources<PersonDTO>> response =
            restClient.exchange(
                restClient.getServiceURI(PERSON_URL),
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<PagedResources<PersonDTO>>() {
                });
PagedResources<PersonDTO> resBody = response.getBody();
        return resBody.getContent();// Returns a collection 
...