2015-09-07 134 views
1

Spring MVC請求映射搜索最接近的匹配參數。 今天我們剛剛遇到一個很好的例子,爲什麼這個當前的實現有問題。 我們有2個功能:Spring MVC @RequestMapping params問題

@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 

用戶希望只刪除史密斯,約翰還以爲他們可以添加一個生日。 但是由於第一個函數沒有得到日期並且用戶犯了一個錯誤,並且在那裏放了一個日期,在我們的例子中,使用了第二個函數,因爲它是最接近匹配的。我仍然不知道爲什麼第二,而不是第一。

結果是所有姓史密斯的人都出生在......被刪除。

這是一個真正的問題!因爲我們只想刪除一個特定的人,但最終刪除了很多人。

有沒有解決方案?

回答

1

更新:

的問題來自於,有你的功能和用戶之間重疊的變量的事實企圖使用它們的混合。爲了確保這個特定的問題不會發生,你可以明確聲明你不想接受包含某些額外變量(當不需要該參數時)的請求。例如,如以上問題可以通過改變第二定義(!注意的firstName PARAM)來解決:

@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) 
+0

感謝錯字修復,但這只是在我的問題中的錯字不在真實的場景中。 – igreen

+0

你說得對,但如果重疊更復雜,排列更多,會怎樣呢?我需要編寫所有不需要的參數?如果春天讓我說我只想要這個參數,這不是很好嗎? – igreen

+1

我認爲沒有標準的方法來切換這個智能請求映射邏輯。我發現最近的是這個主題:http://stackoverflow.com/questions/31364657/can-spring-mvc-strictly-map-query-strings-to-request-parameters –