当用户查询 / rest / data?page = 1& limit = 20 Pageable 对象注入 @GET 带注释的处理程序>根据本指南填充参数
http://docs.spring.io/spring-data/rest/docs/2.0.0.M1/reference/html/paging-chapter.html
@GET
@Path("/rest/data")
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF8"})
public List<SanomalokiDTO> getData(Pageable pageable) {
return service.getData(pageable);
}
但是,我收到以下错误
SEVERE: No message body reader has been found for class org.springframework.data
.domain.Pageable, ContentType: application/octet-stream
elo 19, 2016 12:06:24 IP. org.apache.cxf.jaxrs.impl.WebApplicationExceptionMappe
r toResponse
WARNING: javax.ws.rs.WebApplicationException: HTTP 415 Unsupported Media Type
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.
java:1315)
...
我尝试将@Consumes({MediaType.APPLICATION_OCTET_STREAM})
注释添加到处理程序但仍然得到相同的错误。似乎jax-rs正在尝试从空消息体而不是url参数构建对象。如何将可分页对象绑定到这些参数并将其注入而无需注入 @RequestParam 并手动构建它?
答案 0 :(得分:1)
您必须使用BeanParam注释来注释pagable参数。然后在Pageable中,您必须使用QueryParam
为字段添加注释这样的事情:
@GET
@Path("/rest/data")
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF8"})
public List<SanomalokiDTO> getData(@BeanParam Pageable pageable) {
return service.getData(pageable);
}
你的Pageable课程:
public class Pageable {
@QueryParam("page")
private Integer page;
@QueryParam("limit")
private Integer limit;
...
}
如果您无法控制Pageable类,可以按照以下方式进行操作:
public class PageableBuilder {
@QueryParam("page")
private Integer page;
@QueryParam("limit")
private Integer limit;
...
public Pageable build() {
//create Pageable object
}
}
在资源中:
@GET
@Path("/rest/data")
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF8"})
public List<SanomalokiDTO> getData(@BeanParam PageableBuilder pageableBuilder) {
return service.getData(pageableBuilder.create());
}
答案 1 :(得分:0)
您可以使用@BeanParam
功能映射查询参数并手动构建PageRequest
(请记住pageNumber是零索引的)。
@GET
@Path("/rest/data")
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF8"})
public List<SanomalokiDTO> getData(@BeanParam MyPageRequest myPageRequest) {
PageRequest pageRequest = new PageRequest(myPageRequest.page, myPageRequest.limit);
return service.getData(pageRequest);
}
和
class MyPageRequest {
@QueryParam("page")
public int page;
@QueryParam("limit")
public int limit;
}