Spring MVC 请求映射搜索最接近的参数匹配。 我们今天刚刚遇到一个很好的例子,为什么当前的实现是有问题的。 我们有 2 个函数:
@RequestMapping(method = Array[RequestMethod](RequestMethod.DELETE), params = Array[String]("lastName", "firstName"), produces = Array[String]("application/json"))
def deletePersons1(request: HttpServletRequest, @RequestParam("lastName") lastName: String, @RequestParam("firstName") acref: String)
@RequestMapping(method = Array[RequestMethod](RequestMethod.DELETE), params = Array[String]("lastName", "birthDate"), produces = Array[String]("application/json"))
def deletePersons2(request: HttpServletRequest, @RequestParam("lastName") lastName: String, @RequestParam("birthDate") birthDate: Date)
http 请求是:
DELETE http://host:port/deletePersons?lastName=smith&firstName=john&birthDate=08-10-2015
用户只想删除史密斯、约翰,并且还认为他们可以添加出生日期。 但是,由于第一个函数没有获取日期,并且用户犯了一个错误并在那里输入了日期,因此在我们的例子中,使用了第二个函数,因为它最接近匹配。我仍然不知道为什么是第二个而不是第一个。
结果是,所有出生于...、姓史密斯的人都被删除了。
这确实是个问题!因为我们只想删除一个特定的人,但最终删除了许多其他人。
有什么解决办法吗?
最佳答案
更新:
问题源于这样一个事实:您的函数之间存在重叠变量,并且用户尝试混合使用它们。为了确保此特定问题不会再次发生,您可以明确声明您不希望接受包含某些额外变量的请求(当不需要该参数时)。例如,上面的示例问题可以通过更改第二个定义来解决(注意 !firstName 参数):
@RequestMapping(method = Array[RequestMethod](RequestMethod.DELETE), params = Array[String]("lastName", "birthDate"), produces = Array[String]("application/json"))
def deletePersons2(request: HttpServletRequest, @RequestParam("lastName") lastName: String, @RequestParam("birthDate") birthDate: Date)
至:
@RequestMapping(method = Array[RequestMethod](RequestMethod.DELETE), params = Array[String]("!firstName", "lastName", "birthDate"), produces = Array[String]("application/json"))
def deletePersons2(request: HttpServletRequest, @RequestParam("lastName") lastName: String, @RequestParam("birthDate") birthDate: Date)
关于java - Spring MVC @RequestMapping 参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32443224/