我想使用一个URL映射/all
带请求参数(month
,date
)或不带参数
我尝试创建两种方法,一种不带参数:
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getAll() {
}
其中一个带有参数:
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getByMonth(@RequestParam int month, @RequestParam(required = false) int year) {
}
但是我得到“发现模糊映射” IllegalStateException
。 Spring有什么办法可以解决这种情况?
注意:-,因为我有不同的情况,请不要建议这个solution。
答案 0 :(得分:1)
不可能使用同一路径进行两个不同的映射。 但是也许您可以执行以下操作:
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getByMonth(@RequestParam Integer month, @RequestParam(required = false) Integer year) {
if(month == null && year == null) {
return getAll();
} else {
return getByMonth(month, year);
}
}
或者您可以在第二个映射上将一个变量更改为路径变量
@RequestMapping(value = "/all/{month}", method = RequestMethod.GET)
public CommonResponse getByMonth(@PathVariable("month") Integer month, @RequestParam(required = false) int year) {
}
答案 1 :(得分:1)
您不能为同一个网址创建两个方法,必须将month参数设为可选,并在代码中检查月份是否存在。
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getAllOrByMonth(@RequestParam(required = false) Integer month,
@RequestParam(required = false) Integer year) {
if (month != null) {
// Get by month
} else {
// Get all
}
}
答案 2 :(得分:1)
我找到了解决方案:)
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getAll(@RequestParam(required = false) Optional<Integer> month,
@RequestParam(required = false, defaultValue = "0") int year) {
if (month.isPresent()) {
return getByMonth(month.get, year);
}
return getAll();
}