首页 > 解决方案 > 在 Spring Boot RestController 中区分带有查询参数的端点与没有查询参数的端点

问题描述

如何区分具有查询参数的端点与休息控制器中没有查询参数的端点?下面的映射会引发此错误 -

引起:java.lang.IllegalStateException:不明确的映射。无法映射“itemController”方法

@GetMapping("/")
@ResponseStatus(HttpStatus.OK)
public List<Item> getAllItems(){
    return menuService.getAllItems();
}


@GetMapping("/")
@ResponseStatus(HttpStatus.OK)
public List<Item> getAllItems(@RequestParam("itemtype") ItemType itemType){
    return menuService.findItemsByItemType(itemType);
}

标签: javaspringspring-boot

解决方案


使参数可选:

@GetMapping("/")
@ResponseStatus(HttpStatus.OK)
public List<Item> getAllItems(@RequestParam(name = "itemtype", required = false) ItemType itemType){
    if (itemType == null)
        return menuService.getAllItems();
    return menuService.findItemsByItemType(itemType);
}

推荐阅读