简体   繁体   English

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

[英]How to handle null value in the request in Spring Boot?

I have a rest API where I need to send page num as query parameter. 我有一个Rest API,我需要在其中发送页面num作为查询参数。 When I send null, it gives me a bad request. 当我发送null时,它给了我一个错误的请求。 Below is the rest API code 以下是其余的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";
} 

I am hitting the API with the following URL http://localhost:8000/sample?pageNumber=null 我正在使用以下URL http:// localhost:8000 / sample?pageNumber = null来访问API

I am getting the below 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\"",

How do I handle null case? 如何处理空值?

While hitting any HTTP request, if you don't want to send any value of any request parameter, then please don't include that specific parameter in URL instead of sending null value to that parameter. 在遇到任何HTTP请求时,如果您不想发送任何请求参数的任何值,那么请不要在URL中包含该特定参数,而不是向该参数发送空值。

For eg If you don't want to send any value in pageNumber request parameter, then please don't include pageNumber in request parameter. 例如,如果您不想在pageNumber请求参数中发送任何值,请不要在请求参数中包含pageNumber。 So your request URL will be: http://localhost:8000/sample 因此,您的请求网址将为: http://localhost:8000/sample

If you will hit URL something like http://localhost:8000/sample?pageNumber=null , then it will map "null" string literal to pageNumber request param, and you will get following exception: 如果您将命中类似http://localhost:8000/sample?pageNumber=null类的URL,则它将“ null”字符串文字映射到pageNumber请求参数,并且您将得到以下异常:

"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\\"", “未能将类型'java.lang.String'的值转换为必需的类型'java.lang.Integer';嵌套的异常是java.lang.NumberFormatException:对于输入字符串:\\“ null \\””,

because you are expecting an Integer value that should be mapped with pageNumber request parameter not a string literal. 因为您期望一个Integer值应该与pageNumber请求参数而不是字符串文字进行映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM