Just found a way to do this without using multiple methods.
First, create a simple class to store the path variables:
public class EmployeesRequest { private String value; private String id; public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } }
Then define your controller method as follows:
@RequestMapping(value={ "/abcd", "/employees/{value}/{id}" }) public String getEmployees(@RequestParam(value="param", required=false) String param, EmployeesRequest request) { if (request.getValue() != null) { // do something } else { // do something else } }
Spring automatically maps any path variables available to the EmployeesRequest class. Spring will also do this for any query parameters, so you can simplify things by adding a query parameter to EmployeesRequest :
public class EmployeesRequest { private String value; private String id; private String param; public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getParam() { return this.param; } public void setParam(String param) { this.param = param; } }
And finally:
@RequestMapping(value={ "/abcd", "/employees/{value}/{id}" }) public String getEmployees(EmployeesRequest request) { if (request.getValue() != null) { // do something } else { // do something else } }
An additional advantage of this solution is that now you can support both variables and query parameters. The meaning of all of them would be correct:
/abcd/abcd?param=123/abcd?value=123&id=456¶m=789/employees/123/456/employees/123/456?param=123
source share