Reputation: 1232
I'd like to use one URL mapping /all
with request parameters (month
, date
) or without parameters.
I've tried to create two methods, one without parameters:
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getAll() {
}
And one with parameters:
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getByMonth(@RequestParam int month, @RequestParam(required = false) int year) {
}
But i am getting "Ambiguous mapping found" IllegalStateException
. Does Spring have any way to handle this situation?
Note:- Please don't suggest this solution because I have different scenario.
Upvotes: 2
Views: 1958
Reputation: 1
You can use like this:
@RequestMapping(value = "/all", method = RequestMethod.GET)
public CommonResponse getAll() {
}
@RequestMapping(value = "/all", params = {"month", "date"}, method =
RequestMethod.GET)
public CommonResponse getByMonth(@RequestParam("month") int
month,@RequestParam("date") int date, @RequestParam(required = false) int year)
{
}
Upvotes: 0
Reputation: 1232
I got the solution :)
@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();
}
Upvotes: 1
Reputation: 2313
You can't create two methods for the same url, you have to make your month param optional, and check in code if the month is present or not.
@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
}
}
Upvotes: 1
Reputation: 109
Two different mappings with same path is impossible. But maybe you can do something like this :
@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);
}
}
Or you can change one variable to a path variable on your second mapping
@RequestMapping(value = "/all/{month}", method = RequestMethod.GET)
public CommonResponse getByMonth(@PathVariable("month") Integer month, @RequestParam(required = false) int year) {
}
Upvotes: 1