java - 在 @PathVariable 和 @RequestParam 中使参数可选

标签 java spring spring-boot boot

我正在制作一个 Controller ,它接受两个参数作为@PathVariable,并且我想让第二个参数可选,所以我这样做了->

@GetMapping(value = {"${URL.COACH.GET.ALL.COACH.BY.CORPORATE.NAME}"})
public ResponseEntity<List<CoachRelatedDetails>> getCoachDetailsByCorporateName(@PathVariable String corporateName , @PathVariable(required = false) RoleType roleType){
    System.out.println("ins controller");
    return coachFacade.getCoachDetails(corporateName,roleType);
}

哪里->

URL.COACH.GET.ALL.COACH.BY.CORPORATE.NAME=/getAllCoachByCorporateName/{corporateName}/{roleType}

我在第二个参数中添加了 required = false 。 但是当像这样调用它时,它会给出错误:找不到路径 http://localhost:8080/getAllCoachByCorporateName/ABC/

在使用 @RequestParam 执行相同的操作时,我遇到了相同的错误

@GetMapping(value = {"${URL.COACH.GET.ALL.COACH.BY.CORPORATE.NAME}"})
public ResponseEntity<List<CoachRelatedDetails>> getCoachDetailsByCorporateName
                 (@RequestParam String corporateName,
                  @RequestParam(required = false ) RoleType roleType) {
    System.out.println("ins controller");
    return coachFacade.getCoachDetails(corporateName, roleType);
}

http://localhost:8080/getAllCoachByCorporateName?corporateName=ABC

我在网上找到了相关文章,他们也是这样做的。我不知道我哪里出了问题。

最佳答案

我假设 RoleType 是一种枚举类型,如果是的话,您需要在 Pathvariable 的情况下创建一个处理程序端点,如下所示:

    @GetMapping(value = {"/testing/{corporateName}"})
    public ResponseEntity<List<CoachRelatedDetails>>getCoachDetailsByCorporateNameOnly(@PathVariable String corporateName) {
        System.out.println("when role type is optional call getCoachDetailsByCorporateNameOnly() ");
        return coachFacade.getCoachDetails(corporateName);
    }

For RequestParam you can refer my answer on this

关于java - 在 @PathVariable 和 @RequestParam 中使参数可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76612323/

相关文章:

java - 为什么类字段不被覆盖

java - Log4j - 每个线程的文件日志

JavaFX + Spring Boot + JPA-NullPointerException

Java Spring Security ionic4 HTTP 请求

java - 使用 XSD 中的元素 "anyAttribute"和 "any"将 XML 编码为 Java

java - 如何在 HQL 中获取已删除的行数

java - 没有定义类型的唯一 bean : expected single matching bean but found 2

java - Spring Boot Maven webapp 文件夹和 ResourceHandler

java - Spring:为什么要有多个缓存

Spring 更新调度程序