简体   繁体   中英

SpringBoot Controller mapping to incorrect method

I have below 2 GET mappings in my controller:

1. @GetMapping("/department/{deptId}/employee/{employeeId}")
public String func1(@PathVariable(value = "deptId", required = true) String deptId, 
                    @PathVariable(value = "employeeId", required = true) String employeeId) { ... }
2. @GetMapping("/department/{deptId}/employee/{employeeId}/workLogs")
public String func2(@PathVariable(value = "deptId", required = true) String deptId, 
                    @PathVariable(value = "employeeId", required = true) String employeeId) { ... }

When I Fire the API as:

GET http://localhost:8080/department/102/employee//workLogs --> Keeping employeeId as blank, this call gets mapped to the first GetMapping (func1) and employeeId is calculated as employeeId = "workLogs" .

Hence, There is no exception thrown for missing path variable which was marked as required and call completed with 200 OK.

How to resolve this, so that it maps correctly to func2, and throws an exception for missing required path variable.

When you make a request http://localhost:8080/department/102/employee/workLogs This will be interpreted as workLogs being provided as the employeeId.

There's a couple ways to solve the problem.

  • In func1 , throw an exception if employeeId.equals("workLogs")
  • set employeeId as an Int or Long, so that an exception will be thrown by default when workLogs is attempted to be parsed as an employeeId

But actually, calling http://localhost:8080/department/102/employee//workLogs with the double slash ( // ) should result in a 404 error. Try using version 5.3.15 of Spring if this isn't the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM