我在 Controller 获取请求时定义了一个路径变量:
@PathVariable("ticketId") final Long ticketId
如何检查此值不为空?
阅读 https://www.baeldung.com/spring-validate-requestparam-pathvariable @NotBlank
被使用,但没有提到检查 null。
使用:
if ticketId == Null {
//return message indicating to user that null has been passed to path
}
似乎是一种不好的做法,应该使用 try/catch
代替?
最佳答案
您可以使用注释 @NotNull
来验证传递的参数不是 null
。但是,它仅适用于 Long
等对象类型。如果您使用原始数据类型 long
,则无法使用注释。
@PathVariable("ticketId") @NotNull final Long ticketId
我更推荐使用 long
,根据定义,它不能为 null
。
或者,您可以抛出 ResponseStatusException
如果有更高级的验证传入参数的逻辑。这种方法的优点是 HTTP 状态被传播到最终响应。以下示例结果为 400 Bad Request
:
if (ticketId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticketId cannot be null");
}
关于java - Spring - 在 Controller 中检查路径变量是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61085412/