首页 > 解决方案 > 使用 Spring,我可以创建几个可选的路径变量吗?

问题描述

我尝试像这样在 Spring 中使用几个可选的路径变量,/country/region/city/Chicago/street或者/country/USA/region/Indiana/city/street/我只想为此使用一种方法

@GetMapping(value = "/country/{country}/region/{region}/city/{city}/street/{street}")
public Street getStreet(@PathVariable String country,
                        @PathVariable String region,
                        @PathVariable String city,
                        @PathVariable String street) {
    return new Street ();
}

但是如果我想使用多个路径变量,我必须使用 @GetMapping 注释的所有值组合,比如

@GetMapping(value = {
                        "/country/{country}/region/{region}/city/{city}/street/{street}",
                        "/country/region/{region}/city/{city}/street/{street}",
                        "/country/{country}/region/city/{city}/street/{street}",
                        /*
                          intermediate combinations
                        */
                        "/country/region/city/street/",
                    })
public Street getStreet(@PathVariable(required = false) String country,
                        @PathVariable(required = false) String region,
                        @PathVariable(required = false) String city,
                        @PathVariable(required = false) String street) {
    return new Street ();
}

如何减少组合的数量?也许,最好的方法是使用@RequestParam,但我必须使用@PathVariable

标签: javaspringrest

解决方案


推荐阅读