非null验证不适用于以下情况:
@RestController
public class BookController {
@GetMapping("/api/books/search")
public Page<Book> get(@RequestParam(name = "bookId") @Valid @NotNull Long bookId, Pageable pageable) {
.... // #1
}
}
如果我致电GET http://localhost:8080/api/books/search?bookId=
在第1行上,bookId为null。这是奇怪的行为,因为如果我不提供bookId,它将失败。
@NotNull
验证不会触发。
答案 0 :(得分:2)
@NotNull
验证未触发。
当您希望触发验证时,必须使用@Validated
来注释控制器类:
@Validated
@RestController
public class BookController {
...
}
要有资格通过Spring驱动的方法验证,所有目标类都必须使用Spring的
@Validated
注释进行注释。
@RequestParam
注释具有一个required
元素,其中默认值为true
。它只是表明参数本身必须出现在URL中(?id
或?id=
),但是它不需要该参数的非null值。如果需要验证此类参数的值,则应使用Bean验证批注。
例如,考虑以下控制器方法:
@GetMapping("/foo")
public ResponseEntity<Foo> get(@RequestParam("id") Long id) {
...
}
以下请求将导致状态代码为400
的响应,因为不存在id
参数:
GET /foo HTTP/1.1
Host: example.org
另一方面,以下请求被认为是有效的,因为存在id
参数(即使没有相关的值):
GET /foo?id HTTP/1.1
Host: example.org
要拒绝null
的值,请使用@NotNull
注释(并确保控制器类已用@Validated
注释):
@GetMapping("/foo")
public ResponseEntity<Foo> get(@RequestParam("id") @NotNull Long id) {
...
}
答案 1 :(得分:0)
有不同的概念。默认情况下,需要使用@RequestParam注释的方法参数。您可以设置@RequestParam(required = false)以禁用此功能。
但是您的参数的类型为Long(对象)。您不能给它,然后默认情况下它将为null(因为您没有设置默认值,例如@RequestParam(defaultValue =))。
最好的方法是设置默认值或检查方法中的null。