gpt4 book ai didi

java - Spring Boot中如何处理请求中的空值?

转载 作者:行者123 更新时间:2023-12-02 11:34:58 25 4
gpt4 key购买 nike

我有一个 REST API,我需要发送页码作为查询参数。当我发送 null 时,它会给我一个错误的请求。下面是其余的API代码

@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 http://localhost:8000/sample?pageNumber=null 访问 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\"",

如何处理 null 情况?

最佳答案

在访问任何 HTTP 请求时,如果您不想发送任何请求参数的任何值,请不要在 URL 中包含该特定参数,而应向该参数发送 null 值。

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

如果您点击类似 http://localhost:8000/sample?pageNumber=null 的 URL,那么它会将“null”字符串文字映射到 pageNumber 请求参数,您将得到以下结果异常(exception):

"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\"",

因为您期望一个整数值,该值应该与 pageNumber 请求参数映射,而不是字符串文字。

关于java - Spring Boot中如何处理请求中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com