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

标签 java spring spring-boot

我有一个 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/

相关文章:

java - java中检查字符串是否可以是IP地址

java - 将 JDateChooser 中的日期插入 Oracle DB

java - RestController 中的 Spring ExceptionHandler

spring - 从 spring 中提取 "component-scan"值

spring - 了解实例变量名称和使用 Spring @Bean 注解创建它的方法

java - Spring CrudRepository 未保存超过 32,000 个字符

java - Spring Boot 与 Thymeleaf - 空上下文

java - 我可以在 Android 应用程序的 NavigationView 项目中使用 Google 登录吗?

java - 只允许在 REST API 中使用 PUT 的某些字段(Spring)

java - 将 JSON 数组发布到 Spring Boot 2 JPA 中