@RequestParam 接收参数的值为null的处理方式,
分享于 点击 7724 次 点评:4
@RequestParam 接收参数的值为null的处理方式,
目录
- @RequestParam 接收参数的值为null
- 对于@RequestParam的一些小疑问
- 问题一
- 问题二
@RequestParam 接收参数的值为null
@RequestMapping(value = "/test") public String test( @RequestParam(value = "profit",required = false,defaultValue = "0") int profit){ System.out.println("profit:"+profit); return "success"; }
第一种处理方式(如上图):defaultValue请求参数的默认值,一般和 required = false 一起使用
第二种处理方式:接收的参数如果是null的话,int就要改为Integer,Integer默认值为null
@RequestMapping(value = "/test") public String test(@RequestParam( @RequestParam(value = "profit",required = false) Integer profit){ System.out.println("profit:"+profit); return "success"; }
对于@RequestParam的一些小疑问
问题一
首先我在使用spring时一直使用@RequestParam来校验参数是否为空,但是我想我对@RequestParam的用法产出了一些误解。
简单来说@RequestParam只能验证你有没有传这个参数,而不能验证你传的参数是否为空。
问题二
还有一个问题,有一次我写一个代码如下:method(@RequestParam User user),然后报错如下:Required XXX parameter 'xxx' is not present
把@RequestParam删除就行了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。
您可能感兴趣的文章:- 使用@RequestParam设置默认可以传空值
- 关于Springboot | @RequestBody 接收到的参数对象属性为空的问题
- Spring Boot中@RequestParam参数的5种情况说明
- 解决Springboot 2 的@RequestParam接收数组异常问题
用户点评