java 如何在@RequestParam() 中将默认值设为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47813925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:49:40  来源:igfitidea点击:

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

javaspring-boot

提问by Siddhesh

I'm new to spring bootand learning @RequestParam()

我是Spring Boot和学习的新手@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.

我知道我们可以在 String 中提供 defaultValue 但是当我尝试将默认值提供为 Integer 时,它向我显示了一个错误。

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

any help would be appreciated.

任何帮助,将不胜感激。

回答by Ajay Dsouza

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

尝试在整数周围使用 "" 使其成为字符串,因为 defaultValue 是作为字符串实现的。

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

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

参考:https: //jira.spring.io/browse/SPR-5915

回答by Fabiano Oliveira

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:

当一个值流量通过 HTTP 协议时,它没有类型。它是一个字符串。所以它是在注释处的这个参数类型。然后,你做这样的事情:

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

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

And it will work fine.

它会正常工作。

回答by pvpkiran

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

默认情况下,您传递给控制器​​的任何内容都被视为字符串并转换为相应的类型。所以即使是默认值也需要设置为 String