好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

@RequestParam 接收参数的值为null的处理方式

@RequestParam 接收参数的值为null

?

1

2

3

4

5

@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

?

1

2

3

4

5

6

@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删除就行了

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/Qyq0498/article/details/107953794

查看更多关于@RequestParam 接收参数的值为null的处理方式的详细内容...

  阅读:28次