Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Spring Boot中处理请求中的空值?_Java_Spring_Spring Boot - Fatal编程技术网

Java 如何在Spring Boot中处理请求中的空值?

Java 如何在Spring Boot中处理请求中的空值?,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个RESTAPI,在这里我需要发送page num作为查询参数。 当我发送null时,它会给我一个错误的请求。 下面是RESTAPI代码 @RequestMapping(value = "/sample", method = RequestMethod.GET) @ResponseBody public String sample( @RequestParam(value = "page-number", required = false, defaultValue =

我有一个RESTAPI,在这里我需要发送page num作为查询参数。 当我发送null时,它会给我一个错误的请求。 下面是RESTAPI代码

@RequestMapping(value = "/sample", method = RequestMethod.GET)

@ResponseBody
public String sample(
        @RequestParam(value = "page-number", required = false, defaultValue = "1")  final Integer pageNumber,
        @RequestParam(value = "page-size", required = false, defaultValue = "50")  final Integer pageSize) {

    return "hello";
} 
我正在使用以下URL访问API

我得到下面的例外

"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"null\"",

如何处理空值?

在点击任何HTTP请求时,如果您不想发送任何请求参数的任何值,请不要在URL中包含该特定参数,而不要向该参数发送空值

例如。 若您不想在pageNumber请求参数中发送任何值,那个么请不要在请求参数中包含pageNumber。 因此,您的请求URL将是:
http://localhost:8000/sample

如果你点击URL,比如
http://localhost:8000/sample?pageNumber=null
,然后它将“null”字符串文本映射到pageNumber请求参数,您将得到以下异常:

无法将“java.lang.String”类型的值转换为所需类型 'java.lang.Integer';嵌套异常为 java.lang.NumberFormatException:对于输入字符串:\“null\”


因为您需要的是一个应与pageNumber请求参数(而不是字符串文字)映射的整数值。

不要尝试传递
null
,只需从URL中删除该参数即可。异常清楚地说明了问题所在。为什么要发送null?应该是你的URL。我已经理解了这个异常,这是因为null被认为是字符串,但是如果它被传递,我该如何处理它呢@MehrajMalikAnd如何处理错误的参数名?它是否可以用预定义的异常捕获并相应地处理?