2014-03-07 19 views
0

我有問題就像標題。我知道彈簧mvc中有一個@RequesetParam,它有一個參數required=false。但嘗試使用它卻失敗了。如何處理值爲root =,帶有鍵和無值的參數?

其實我發現@RequestParam是沒用的。根據我的努力,它總是O.K.使用@RequestParam(value="root", required=true),其中URL有/無value=some value except blank。 所以,我不知道required=true是什麼。然後,無論required=falserequired=true是什麼,它都會拋出異常,並使用URL參數...&root=

而且我的HandlerMapping & AdapterMapping被RequestMappingHandlerMapping和RequestMappingHandlerAdapter

Spring MVC中的版本是3.2.4

請告訴我發生了什麼事情與Spring MVC的?

感謝提前:)

+0

如果請求中缺少參數,將拋出異常,並且不需要設置'required = true','@ RequestParam'的默認值爲true。 – Rembo

+0

非常感謝。我迷惑了爲什麼@RequestMapping不能處理像&root =這樣的URL參數。 – EdgarZeng

回答

2

根據文檔:

公共抽象布爾需要

是否需要參數。缺省值爲true,導致在請求中缺少參數的情況下引發 異常。 如果在缺少參數 的情況下更喜歡空值,則將其切換爲false。

或者,提供一個defaultValue,它默認將此標誌 設置爲false。

因此,如果參數在請求中缺失,您可以決定是否拋出異常或不拋出異常!

根據你的問題,你都驚歎不已,爲什麼也不例外不扔,這是因爲這兩個網址具有不同的含義:在第一種情況下的價值

http://my-domain.ir:8080/your-project-name/main.html?p=something&root=

http://my-domain.ir:8080/your-project-name/main.html?p=something

存在但它沒有任何值在第二個cas e缺失,你的病例符合第一個條件,這是因爲沒有例外。

//if you use the code below, in your case the root will get no value exactly like you define String root ="" 
@RequestParam("root") String root 

我建議你總是使用@ModelAttribute在春季和驗證/未驗證類變量,你想與JSR303標準和使用的getter/setter方法收到您的參數值bean類。

+0

感謝您的詳細解釋。我的情況對於第一種情況是正確的。但是,當提交與該網址的請求時,我真正收到異常'... MissingServletRequestParameterException'。 – EdgarZeng

+0

(你說這是因爲沒有異常throw_)。這是我的[spring mvc config](http://paste.ubuntu.com/7048848/)。我已經設置了一些錯誤頁面。但是,如果我的url缺少一些參數(不是_沒有values_,比如沒有像'root = 1'的第二種情況),並且服務器端代碼的'required = true',它不會拋出任何錯誤給我。我認爲它應該給我帶來錯誤。爲什麼會發生這種情況? – EdgarZeng

+0

嘗試下載此附加組件並檢查您的網址是否與您期望的網址一致:https://addons.mozilla.org/en-us/firefox/addon/live-http-headers/ if你在這個工具裏看到了root = prameter,給我發送完整的異常堆棧跟蹤,我讓我看看! – M2hp

1

您應該使用佔位符在URL中獲取價值和使用@PathVariable從URL獲取值,

例如:

@RequestMapping(value="/customer/{customerId}/show", method = RequestMethod.GET) 
public ModelAndView showCustomerById(
      @PathVariable("customerId") int customerId) { 
    ... 
} 

並且請求的URL看起來像:

http://localhost:8080/HelloWorld/customer/1234/show 

如果你想通過上面的參數然後,像這樣做:

@RequestMapping(value="/customer/{customerId}/show", method = RequestMethod.GET) 
public ModelAndView showCustomerByIdAndName(
      @PathVariable("customerId") int customerId, 
      @RequestParam(value = "name", required = false) String name){ 
... 
} 

並且請求的URL看起來像現在:

http://localhost:8080/HelloWorld/customer/1234/show?name=myName 

注:必填字段的默認值是true,如果沒有找到該參數,然後異常會提高。

+0

這是我的問題的解決方案,但我想知道爲什麼春天mvc無法弄清楚具有'...&root ='的URL,它沒有值但不缺少參數。 – EdgarZeng

+0

@EdgarZeng顯示完整網址 – Rembo

+0

完整[URL](http://pastebin.ubuntu.com/7050102/)。 – EdgarZeng