2

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.

Paul Benn
  • 1,911
  • 11
  • 26
Victory
  • 1,184
  • 2
  • 11
  • 30

4 Answers4

1

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) {
    }
Ahmet Amasyalı
  • 109
  • 1
  • 6
1

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
    }
}
b.GHILAS
  • 2,273
  • 1
  • 8
  • 16
  • You can create two method for the same URL, check [this](https://stackoverflow.com/a/15853217/9993404) – Victory Dec 10 '19 at 13:56
1

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();
}
Victory
  • 1,184
  • 2
  • 11
  • 30
0

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) 
{

}