spring - REST API 设计 - 可选请求参数
问题描述
我已经编写了这个请求映射来通过它的 id 访问一张票:
@GetMapping(path = "/tickets/{ticketId}")
@ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<List<TicketResponse>> getTicketsById(@PathVariable("ticketId") final Long ticketId
我打算添加多个查询参数来支持ticketType、ticketStatus等过滤。REST API 用户应该可以选择过滤任何或所有查询参数。
实现这一目标的 REST API 设计原则是什么?我应该添加新的请求参数来支持如下过滤吗?:
@GetMapping(path = "/tickets/{ticketId}")
@ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<List<TicketResponse>> getTicketsById(@PathVariable("ticketId") final Long ticketId, @RequestParam("ticketType") final String ticketType, @RequestParam("ticketStatus") final String ticketStatus)
这种场景是否有 Spring 设计模式?Java builder 模式可用于参数 QueryParameter 对象的属性?
解决方案
你基本上有两个选择:
要么你把你所有的 RequestParams 作为方法参数,但是
required=false
就像@AmitKumar 写的那样。例子:@RequestParam(name="ticketType", required = false) String ticketType
将所有这些参数放入一个,比方说 FilterDTO 并将其作为参数 (
FilterDTO filter
)。Spring 将确保使用您的 RequestParams 填充其字段。只需将您的 ticketType 和其他参数作为字段放入 DTO,它们将是可选的。例子:public ResponseEntity<List<TicketResponse>> getTicketsById(@PathVariable("ticketId") ong ticketId, FilterDto filter){}
推荐阅读
- javascript - 将表单字段设为字母数字时无法读取未定义的属性“匹配”
- javascript - onchange 必须从它正在存储值的计数器中删除值
- java - Solr 有时会停止为生产中的查询返回结果。
- android - 通过在 URL 中输入路径打开 PDF 文件
- database - 正确的 Google Cloud 产品
- php - docker-php-ext-configure、docker-php-ext-install 和 docker-php-ext-enable 有什么作用?
- java - 启动层初始化时出错
- excel-formula - 在 Excel 中分配数据,使其与汇总数据匹配
- kubernetes - CentOS7:使用 kubeadm 引导 kubernetes 集群时提取映像配置时出错
- android - 如何将地图视图添加到我的 Android 应用程序 FragmentActivity