是否可以让空的 RequestParam 值使用 defaultValue? [英] Is it possible to have empty RequestParam values use the defaultValue?

查看:37
本文介绍了是否可以让空的 RequestParam 值使用 defaultValue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

if I have a a request mapping similar to the following:

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

然后调用这个请求:

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

我收到错误信息

未能将java.lang.String"类型的值转换为int"类型;嵌套异常是 java.lang.NumberFormatException: For input string: ""'

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

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

I can solve this by either stopping the javascript client from sending empty parameters, or by accepting string values and only parsing if they are not found to be blank.

更新:spring 的更高版本现在实现了最初想要的行为.

UPDATE: Later versions of spring now implement the originally desired behaviour.

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

I've just tested this in spring 4.3.5 and have found that the behaviour will now in fact turn the null value into the default value without raising a NumberFormatException, thus; my original mapping now works fine.

我不确定这个行为改变是在哪个版本的 spring 上做出的.

I am not sure which version of spring this behavioural change was made.

推荐答案

您可以将@RequestParam 类型更改为整数并使其不再需要.这将使您的请求成功,但它将为空.您可以在控制器方法中将其显式设置为默认值:

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

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

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

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

这篇关于是否可以让空的 RequestParam 值使用 defaultValue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆