I was recently trying to learn Spring and Java 17 as I only have experience with Dropwizard and Java 11, and I would like to do validation on a POJO, in a POST or PUT request.
I've encountered several examples, but locally testing, I don't seem to be able to actually run into the validation, at first I thought it might be a Records issue so I've fallen back to Class and I still cannot validate it, any clues as to what the issue might be?
我的控制器:
@RestController
public class HelloWorldController {
//... other GET APIs
@PostMapping("/userProfile")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<UserProfileClass> addUserProfile(@RequestBody @Valid UserProfileClass userProfile) {
System.out.println("Inserting in the database: " + userProfile);
return ResponseEntity.ok(userProfile);
}
POJO(UserProfileClass):
public class UserProfileClass {
@NotNull @NotBlank String name;
@NotBlank @NotNull String address;
//... getters and setters
包含验证器的pom.xml:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
如果我在本地运行它,并在IntelliJ上发布以下内容:
POST http://localhost:8080/userProfile
Content-Type: application/json
{
"name": "some Name"
}
我总是得到200分,身体是这样的:
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 18 Feb 2024 23:21:46 GMT
Keep-Alive: timeout=60
Connection: keep-alive
{
"name": "some Name",
"address": null
}
正如@NotNull显然不应该让它通过的那样,我假设如果@Valid失败,我会得到某种4xx响应,但这似乎没有发生. 这里遗漏了什么?