【问题标题】:How would you go about creating RESTful services with multiple optional parameters using Spring您将如何使用 Spring 创建具有多个可选参数的 RESTful 服务
【发布时间】:2020-05-14 12:58:03
【问题描述】:

我想构建一个带有多个可选参数的演示 REST 服务。现在我的代码只接受一个参数,如果它不存在,它就会出错。

    @RequestMapping(value = "/family")
    @ResponseBody
    public Optional<Family> getMemberWithParams(@RequestParam("id") String rfamAcc) {
        return rfamRepository.findById(rfamAcc);
    }

因此,当您查询此 URL http://localhost:8080/family?id=RF00009 时,如果 id 正确,您会得到正确的结果。 但是如果我想要多个可选参数呢?我必须为每种可能性编写一个函数还是有一个简单的解决方案?我是否必须对函数进行硬编码,或者我可以这样说:

        @RequestMapping(value = "/family")
        @ResponseBody
        public Optional<Family> getMemberWithParams(@RequestParam("id") String rfam_acc, @RequestParam("somethingElse") String somethingElse) {
            if(notPresent(rfam_acc)){
                return rfamRepository.findBySomethingElse(somethingElse); 
            return rfamRepository.findById(rfam_acc);
        }

【问题讨论】:

    标签: java spring api rest repository


    【解决方案1】:

    您可以将@RequestParam(required=false) 的'required' 属性设置为false,并使用'defaultValue' 属性@RequestParam(value= fieldname, required=false, defaultValue="some default value") 设置默认值

    @PostMapping("/products")
    public ResponseEntity<?> save(
              @RequestParam("name") String name,
              @RequestParam("price") Double price,
              @RequestParam(value ="title", required = false, defaultValue="Product Title") String title,
              @RequestParam(value = "dom", required = false) Date manufactureDate,
              @RequestParam(value = "images", required = false) List<MultipartFile> images) {
        //codes
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 2020-06-04
      • 1970-01-01
      相关资源
      最近更新 更多