简体   繁体   中英

How to give default value as integer in @RequestParam()

I'm new to spring boot and learning @RequestParam()

I know that we can give defaultValue in String but when I am trying to give default value as Integer it's showing me an error.

@RequestMapping("/returnVeriable")
public int getVeriable(@RequestParam(required=true,defaultValue=1/*error here*/) int veri){
    return veri;
}

any help would be appreciated.

Try with "" around integer to make it string as the defaultValue is implemented as String.

@RequestMapping("/returnVeriable")
public int getVeriable(@RequestParam(required=true,defaultValue="1") Integer veri){
    return veri;
}

refer : https://jira.spring.io/browse/SPR-5915

When a value traffic by HTTP protocol, it has no type. It's a String. And so it is at this parameter type at the annotation. Then, you do something like this:

@RequestParam(required = true, defaultValue = "1") Integer veri

And it will work fine.

This should work

@RequestMapping("/returnVariable")
public int getVariable(@RequestParam(required=true,defaultValue="1") int var) {
    return var;
}

By default what ever you pass to the controller is treated as String and converted to respective types. So even default values need to be set as String

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