简体   繁体   中英

Setting RequestParam with default value is always null when value is set

I am creating a rest method that could handle an optional parameter(gender in this case) using RequestParam annotation. But the gender value is always taken as null. (spring version 4.0.0) second param is considered correctly though.

Sample: http://localhost:8080/bll-0.1/qry/gender/female/age/40

@RequestMapping(value = {"/age/{age}", "/gender/{gender}/age/{age}"}, method = RequestMethod.GET)
public @ResponseBody String getByAge(@RequestParam(value="gender", defaultValue="unknown") String gender, @PathVariable("age") int age) throws Exception {...}

Thanks in advance. Pankaj

Like Juned said in comments, use @PathVariable for gender as well.

public @ResponseBody String getByAge(@PathVariable("gender") String gender, @PathVariable("age") int age) throws Exception {...}

If you want optional parameter and it's not a problem if you have request paramter then your url should be somewhat like http://localhost:8080/bll-0.1/qry/age/40?gender=female and you can use @RequestParam

public @ResponseBody String getByAge(@RequestParam(value="gender", defaultValue="unknown") String gender, @PathVariable("age") int age) throws Exception {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM