coder
coder

Reputation: 6233

How do you receive a url parameter with a spring controller mapping

This issue seems trivial, but I can't get it to work properly. I'm calling my Spring controller mapping with jquery ajax. The value for someAttr is always empty string regardless of the value in the url. Please help me determine why.

-URL called

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

-Controller Mapping

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

Upvotes: 144

Views: 265992

Answers (2)

Optio
Optio

Reputation: 7652

You have a lot of variants for using @RequestParam with additional optional elements, e.g.

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

If you don't put required = false - param will be required by default.

defaultValue = "someValue" - the default value to use as a fallback when the request parameter is not provided or has an empty value.

If request and method param are the same - you don't need value = "someAttr"

Upvotes: 35

skaffman
skaffman

Reputation: 403591

You should be using @RequestParam instead of @ModelAttribute, e.g.

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

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

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

Upvotes: 219

Related Questions