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

查看:633
本文介绍了是否有可能使空的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) {
}

然后使用以下命令调用此请求:

And then call this request with:

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

我收到错误消息

无法将'java.lang.String'类型的值转换为'int'类型;嵌套的异常是java.lang.NumberFormatException:对于输入字符串:"'

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.

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

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

我刚刚在春季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类型更改为Integer并使它不是必需的.这将使您的请求成功,但是它将为null.您可以在控制器方法中将其显式设置为默认值:

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天全站免登陆