Spring MVC选择了错误的控制器方法

ams*_*ams 6 spring spring-mvc

在我的应用程序中,我遇到一种情况,即spring mvc始终选择错误的控制器方法来执行.从下面的弹簧调试日志显示问题,它找到两个匹配一个用于我的通用处理所有未映射的映射控制器映射到/api/**和一个用于实际的东西我正在寻找api/companies/2/records/cabinets/FileTypes/50/1spring mvc然后选择/api/**处理程序通过更具体的处理程序它找到.

我对spring的理解是,如果请求映射有两个匹配项,那么spring将使用更长的url选择handle方法.为什么spring mvc选择较短的映射?

给定以下映射:

  • /api/companies/{id}/records/cabinets/FileTypes/{fileTypeId}/{versionId} 映射到method1
  • /api/** 映射到method2

api/companies/2/records/cabinets/FileTypes/50/1应该将mvc选择的路径作为上述两个url的处理程序方法.

这里是调试日志的相关行.

17:58:49,858 DEBUG [DispatcherServlet] DispatcherServlet with name 'main' processing PUT request for [/web/api/companies/2/records/cabinets/FileTypes/50/1]
17:58:49,858 TRACE [DispatcherServlet] Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@2b25f2be] in DispatcherServlet with name 'main'
7:58:49,858 DEBUG [RequestMappingHandlerMapping] Looking up handler method for path /api/companies/2/records/cabinets/FileTypes/50/1
17:58:49,859 TRACE [RequestMappingHandlerMapping] Found 2 matching mapping(s) for [/api/companies/2/records/cabinets/FileTypes/50/1] : [{[/api/**],methods=[PUT],params=[],headers=[],consumes=[],produces=[],custom=[]}, {[/api/companies/{id}/records/cabinets/FileTypes/{fileTypeId}/{versionId}],methods=[PUT],params=[],headers=[],consumes=[],produces=[],custom=[]}]
Run Code Online (Sandbox Code Playgroud)

acd*_*ior 7

这确实是一个错误(见这里这里).

我相信映射考虑了第一个表达式中括号的数量:

/api/companies/{id}/records/cabinets/FileTypes/{fileTypeId}/{versionId}
               ^--                             ^--          ^--
Run Code Online (Sandbox Code Playgroud)

由于第一个中有三个括号(模式),而**第二个中只有一个模式(),因此第一个被认为是更一般的.

解决方法:

作为*/*以同样的方式计算,尝试使第二个表达式,而不是/api/**像:

/api/**/**/**/**
Run Code Online (Sandbox Code Playgroud)

这有四种模式,因此比其他模式"更通用".但在实践中,它相当于/api/**.这将使其最后评估.

由于存在这种有点"简单"的解决方法,我相信如果有的话,该错误需要很长时间才能得到纠正.