gpt4 book ai didi

java - 是否可以让空的 RequestParam 值使用 defaultValue?

转载 作者:IT老高 更新时间:2023-10-28 11:24:16 27 4
gpt4 key购买 nike

如果我有一个类似于以下的请求映射:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", defaultValue = "10") int i) {
}

然后调用这个请求:

http://example.com/test?i=

我收到错误消息

Failed to convert value of type 'java.lang.String' to type 'int'; nested exception is java.lang.NumberFormatException: For input string: ""'

我可以通过阻止 javascript 客户端发送空参数来解决此问题,或者通过接受字符串值并仅在未发现它们为空时进行解析。

更新:更高版本的 spring 现在实现了最初期望的行为。

我刚刚在 spring 4.3.5 中对此进行了测试,发现现在的行为实际上会将 null 值转换为默认值,而不会引发 NumberFormatException,因此;我的原始映射现在可以正常工作了。

我不确定这种行为改变是哪个版本的 spring。

最佳答案

您可以将 @RequestParam 类型更改为 Integer 并使其不需要。这将使您的请求成功,但它将为空。您可以在 Controller 方法中将其显式设置为默认值:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
if(i == null) {
i = 10;
}
// ...
}

我已经从上面的示例中删除了 defaultValue,但是如果您希望收到根本没有设置的请求,您可能需要包含它:

http://example.com/test

关于java - 是否可以让空的 RequestParam 值使用 defaultValue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12296642/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com