Spring Controller适配指定URL异常求助:请求参数匹配失败
Got it, let's break down why your test URL is throwing that "This application has no explicit mapping..." error—it's all about mismatched request patterns!
问题根源
你的测试URL使用的是查询参数(也就是?projectId=1;fileId=1这部分):
http://localhost:8080/home/filter?projectId=1;fileId=1
但你的Controller方法配置的是路径变量(URL路径里的{projectId}/{fileId}占位符):
@GetMapping("/home/filter/{projectId}/{fileId}") public String filter(@PathVariable("projectId") int projectId, @PathVariable("fileId") int fileId) { // ... 你的代码 }
Spring无法将基于查询参数的URL映射到基于路径变量的Controller方法,所以返回了404错误(就是你看到的提示)。
两种解决方案
方案1:修改Controller适配现有URL
如果你想继续用原来的测试URL,把Controller里的@PathVariable换成@RequestParam来获取查询参数:
@GetMapping("/home/filter") public String filter(@RequestParam("projectId") int projectId, @RequestParam("fileId") int fileId) { System.out.println("Project Id " + projectId); System.out.println("File Id " + fileId); return "redirect:/home"; }
这个方法可以完美匹配http://localhost:8080/home/filter?projectId=1;fileId=1,也支持更通用的&分隔参数形式:http://localhost:8080/home/filter?projectId=1&fileId=1。
方案2:修改测试URL适配现有Controller
如果你想保留原来的Controller代码,把测试URL改成路径变量的形式:
http://localhost:8080/home/filter/1/1
这个URL会和@GetMapping("/home/filter/{projectId}/{fileId}")的映射匹配,路径里的1和1会自动绑定到projectId和fileId参数上。
额外小提示
如果你确实需要支持矩阵参数(就是你原URL里用;分隔的参数形式),需要在Spring里手动开启矩阵变量支持(默认@RequestMapping是禁用的)。不过大多数场景下,上面两种方案已经能解决问题了。
内容的提问来源于stack exchange,提问作者abc

