Spring – 在控制器中检查路径变量是否为空

huangapple go评论80阅读模式
英文:

Spring - checking path variable for null at controller

问题

我在控制器的Get请求中定义了一个路径变量:

@PathVariable("ticketId") final Long ticketId

我该如何检查这个值不为空?

阅读 https://www.baeldung.com/spring-validate-requestparam-pathvariable ,其中使用了 @NotBlank,但没有提到检查null。

使用:

if (ticketId == null) {
//返回消息,提示用户路径传递了空值
}

似乎是一种不好的做法,应该使用 try/catch 来代替?

英文:

I define a path variable at controller Get request using:

@PathVariable("ticketId") final Long ticketId

How can I check this value is not null ?

Reading https://www.baeldung.com/spring-validate-requestparam-pathvariable @NotBlank is utilised but checking for null is not mentioned.

Using:

if ticketId == Null {
//return message indicating to user that null has been passed to path
}

Seems a bad practice and instead try/catch should be used ?

答案1

得分: 6

你可以使用注解 @NotNull,它会验证传入的参数不为 null。然而,它只对像 Long 这样的对象类型起作用。如果你使用原始数据类型 long,则无法使用该注解。

@PathVariable("ticketId") @NotNull final Long ticketId

我更建议使用不可能为 nulllong

另外,如果有更高级的逻辑需要验证传入参数,你可以抛出 ResponseStatusException。这种方法的优势在于 HTTP 状态会传播到最终的响应中。以下示例会导致 400 Bad Request

if (ticketId == null) {
    throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticketId cannot be null");
}
英文:

You can use the annotation @NotNull which validates the passed parameter is not null. However, it works only for the object types like Long. In case you use a primitive data type long, the annotation cannot be used.

@PathVariable("ticketId") @NotNull final Long ticketId

I rather recommend to use long which cannot be null by definition.

Alternatively, you can throw ResponseStatusException if there is more advanced logic of validating the incoming parameters. The advantage of this approach is that the HTTP status is propagated to the final response. The following sample results in 400 Bad Request:

if (ticketId == null) {
    throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticketId cannot be null");
}

答案2

得分: 0

使用@NotBlank来标记字符串类型的数据,对于其他包装类型使用@NotNull,但是对于原始类型来说,@NotNull不起作用,因为它们不会返回null,而是有默认值。

英文:

Use @NotBlank for String datatypes and @NotNull for other Wrapper Types but for Primitve types it wont work as they wont return null as they have a default value.

huangapple
  • 本文由 发表于 2020年4月8日 01:02:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/61085412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定