【问题标题】:How to model custom request params in Spring for JSON API?如何在 Spring 中为 JSON API 建模自定义请求参数?
【发布时间】:2017-10-14 00:59:09
【问题描述】:

我目前正在尝试对JSON API 的查询参数结构进行建模,并将其应用于我的 Spring Boot 项目中。我将专注于filters、排序、分页,也许还有字段限制。

我想先从过滤开始,所以我希望我的 REST 端点能够处理 JSON-API 样式的 URL 请求,例如

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

我的计划是在顶级 JsonApiParams 对象中捕获所有 JSON API 特定的查询参数,例如:

public class JsonApiParams {
  private Filters filters;
  private Sorting sorting;
  private Paging paging;

  // getters, setters
}

然后模拟出FiltersSortingPaging。这个JsonApiParams 对象将在我的@RestController 端点中作为请求参数被接受,如下所示:

@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 json-api


    【解决方案1】:

    幸运的是,开箱即用的 Spring 使用 Maps 的括号表示法。我能够使用以下模型格式化我的 URL 查询参数,如 /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
    }
    

    然后,就我而言,我将过滤器转换为 QueryDSL Predicate,并将 sortpage 字段转换为 Spring Pageable 请求。轻松转换并无缝工作。

    【讨论】:

    • 嗨,Heez,您能详细说明一下吗?不确定如何在 @RequestParam 上使用它
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 2020-04-12
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多