2011-08-11 75 views
56

這個問題看似微不足道,但我無法讓它正常工作。我打電話給我的Spring控制器映射與jQuery的Ajax。無論url中的值如何,someAttr的值始終爲空字符串。請幫我確定原因。如何通過彈簧控制器映射接收url參數

-URL稱爲

http://localhost:8080/sitename/controllerLevelMapping/1?someAttr=6 

-Controller映射

@RequestMapping(value={"/{someID}"}, method=RequestMethod.GET) 
public @ResponseBody int getAttr(@PathVariable(value="someID") final String id, 
     @ModelAttribute(value="someAttr") String someAttr) { 
    //I hit some code here but the value for the ModelAttribute 'someAttr' is empty string. The value for id is correctly set to "1". 
} 

回答

84

您應該使用@RequestParam代替@ModelAttribute,例如

@RequestMapping("/{someID}") 
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
           @RequestParam String someAttr) { 
} 

你甚至可以忽略@RequestParam完全如果你選擇,而Spring會認爲這就是它是:

@RequestMapping("/{someID}") 
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
           String someAttr) { 
} 
8

你有很多變體使用@RequestParam與另外的可選部件,例如

@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr 

如果你不把required = false - 默認情況下需要param。

defaultValue = "someValue" - 當未提供請求參數或具有空值時,用作回退的默認值。

如果請求和方法參數相同 - 您不需要value = "someAttr"