【问题标题】:How to define multiple query parameters in Spring bootSpring boot中如何定义多个查询参数
【发布时间】:2020-12-31 13:07:08
【问题描述】:

我需要获取有关名字、姓氏、手机等多个参数的所需客户信息。
我决定为此使用查询参数。

如果我将我的方法定义如下

@GetMapping("/customers")
    public ResponseEntity<EntityModel<Customer>> findCustomerByFirstName(@RequestParam(required = false) String firstName) {
        System.out.println();
        return service.findCustomerByFirstName(firstName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
    }
//Last-name
@GetMapping("/customers")
    public ResponseEntity<EntityModel<Customer>> findCustomerByLastName(@RequestParam(required = false, name = "lastName") String lastName) {
        return service.findCustomerByLastName(lastName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
    }

春天给了我以下例外。

引起:java.lang.IllegalStateException:不明确的映射。无法映射“customerController”方法 com.test.cas.controller.CustomerController#findCustomerByFirstName(String) 到 {GET [/api/customers/]}:已经有 'customerController' bean 方法 com.test.cas.controller.CustomerController#findCustomerByLastName(String) 映射。

非常感谢任何解决此问题的建议。

【问题讨论】:

  • 您有两个端点具有相同的路径和相同的 HTTP 方法,因此 Spring 无法区分它们。
  • 您的两个端点都可以不带参数调用(每个参数上都有required = "false"),因此无法从中选择。
  • 是的,我的两个端点都是相同的,正在寻找一些建议以按照最佳实践完成我的工作。我可以更改端点,然后我最终会像“/customers/firstname/{firstName}”和“/customers/lastname/{lastName}”我不确定这是否符合最佳实践。在这里需要一些建议。

标签: java spring spring-boot spring-mvc query-parameters


【解决方案1】:

只使用一种映射到一种方法并执行类似的操作。

@GetMapping("/customers")
    public ResponseEntity<EntityModel<Customer>> findCustomerByFirstNameOrLastname(
@RequestParam(required = false) String firstName, 
@RequestParam(required = false) String lastName) {
        if (StringUtils.hasText(firstName))
            return service.findCustomerByFirstName(firstName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
        if (StringUtils.hasText(lastName))
            return service.findCustomerByLastName(lastName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
    }

这可以用 JPA Criteria 规范和一个单独的服务层来编写,但只是为了主要思想。

【讨论】:

  • 我试过了,这个解决方案有效,但我不确定是否有更好的方法,因为我的名字、姓氏和手机号码将返回 ResponseEntity> 但其他参数如 city 和 state 将返回 ResponseEntity> 不能在单个方法中容纳。
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 2021-09-15
  • 2019-07-07
  • 1970-01-01
  • 2020-10-21
  • 2017-11-06
  • 2020-02-21
  • 2019-01-12
相关资源
最近更新 更多