如何通过spring控制器映射接收url参数


问题内容

这个问题看似微不足道,但我无法使其正常工作。我正在用jquery
ajax调用Spring控制器映射。无论URL中的值如何,someAttr的值始终为空字符串。请帮助我确定原因。

-URL称为

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

-控制器映射

@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".
}

问题答案:

您应该使用@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) {
}