【问题标题】:Spring MVC @RequestMapping params issueSpring MVC @RequestMapping 参数问题
【发布时间】:2015-09-07 16:58:08
【问题描述】:

Spring MVC 请求映射搜索参数最接近的匹配。 今天我们刚刚遇到了一个很好的例子,为什么这个当前的实现是有问题的。 我们有两个功能:

@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

用户只想删除 Smith、John,还认为他们可以添加出生日期。 但是由于第一个函数没有得到日期并且用户犯了一个错误并在那里输入了一个日期,所以在我们的例子中,使用了第二个函数,因为它最接近匹配。我仍然不知道为什么是第二个而不是第一个。

结果是所有姓史密斯、出生于...的人都被删除了。

这是一个真正的问题!因为我们只想删除一个特定的人,但最终却删除了许多其他人。

有什么解决办法吗?

【问题讨论】:

    标签: java spring spring-mvc request-mapping


    【解决方案1】:

    更新:

    问题在于您的函数之间存在重叠变量,并且用户试图混合使用它们。为确保此特定问题不会再次发生,您可以明确声明您不想接受包含某些额外变量的请求(当不需要该参数时)。例如,上面的示例问题可以通过更改第二个定义来解决(注意 !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)
    

    【讨论】:

    • 感谢您修复错字,但这只是我的问题中的错字,而不是真实场景。
    • 你说得对,但是如果重叠更复杂,排列更多。我需要写所有不需要的参数吗?如果spring让我说我只想要这个参数不是很好吗?
    • 我认为没有标准的方法来切换这种智能请求映射逻辑。我找到的最接近的是这个主题:stackoverflow.com/questions/31364657/…
    • 你怎么看Jira ticket
    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多