如何在Spring中为JSON API建模自定义请求参数?
问题描述:
我目前正在试图建模JSON API的查询参数结构,并将其应用到我的Spring Boot项目中。我将关注filters,排序,分页和可能的字段限制。如何在Spring中为JSON API建模自定义请求参数?
我想先下手过滤,所以我想我的REST端点能够处理像
GET /comments?filter[post]=1 HTTP/1.1
GET /comments?filter[post]=1,2 HTTP/1.1
GET /comments?filter[post]=1,2&filter[author]=12 HTTP/1.1
JSON-API风格的URL请求,我的计划是捕获所有JSON API特定的查询参数顶级JsonApiParams
对象,如:
public class JsonApiParams {
private Filters filters;
private Sorting sorting;
private Paging paging;
// getters, setters
}
然后模拟出Filters
,Sorting
,Paging
为好。这JsonApiParams
对象将随后在我@RestController
端点像这样被接受的请求PARAM:
@RequestMapping(value = {"/api/v1/{entity}"},
method = RequestMethod.GET,
produces = {"application/vnd.api+json"})
@ResponseBody
public JsonApiTopLevel jsonApiGetByEntity(@PathVariable String entity, JsonApiParams params) {
// convert params to DB query
}
所以,我应该如何建模我JsonApiParams
对象能够处理像上面(例如,/comments?filter[post]=1,2&filter[author]=12
)中的那些要求?
答
幸运的是,Spring开箱即用地图使用括号符号。我能格式化我的网址查询参数这样/comments?filter[post]=1,2&filter[author]=12
以下模型:
public class JsonApiParams {
private Map<String, List<String>> filter;
private List<String> sort;
private Map<JsonApiPaginationKeys, Integer> page;
// getters & setters
}
然后,在我的情况,我转换的过滤器,以一个QueryDSLPredicate
,并sort
和page
领域进入春季Pageable
请求。轻松转换并无缝工作。