neoty
neoty

Reputation: 33

springboot, how to valid @RequestBody

current code

    @Slf4j
    @RestController
    public class TestController {
        @Validated
        @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
        String test( @RequestBody @NotEmpty @Valid List<@NotBlank @Valid UUID> uuids) {
            return uuids.toString();
        }
    }

problem

--header 'Content-Type: application/json' \
--data-raw '[]'

curl --location --request PUT 'localhost:8080' \
--header 'Content-Type: application/json' \
--data-raw '[""]'

valid passes. But i don't want it

I want to validate the curl request in the sample above. Is there any way to do it without dto?

Upvotes: 1

Views: 9380

Answers (2)

HaiZi
HaiZi

Reputation: 309

Add a comment on the field

@Getter
@Setter
public class Person {
    @NotNull(message = "[id] cannot be empty")
    private Long id;

    @NotBlank(message = "[name] cannot be blank")
    private String name;
    @NotBlank(message = "[email] cannot be blank")
    private String email;
    @NotBlank(message = "[birthday] cannot be blank")
    private Date birthday;

    @Override
    public String toString() {
        return JSONUtils.toJSONString(this);
    }
}

Use @Validated for validation

@RestController
@RequestMapping
public class TestController {

    @PostMapping(value = "/get")
    public String get(@Validated @RequestBody Person person) {
        return person.toString();
    }
}

Upvotes: 0

Deepesh Dagar
Deepesh Dagar

Reputation: 201

The correct way of doing it

@Slf4j
@RestController
@Validated
public class TestController {
    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    String test( @RequestBody @NotEmpty @Valid List<@NotNull @Valid UUID> 
     uuids) {
        return uuids.toString();
    }
}

we have to annotate the beans, which shall be validated, with @Validated. Also for UUID @NotNull will suffice the requirement as No validator exists for this constraint for object UUID

Validation Messages can also be customised by providing "message" param for @NotEmpty and @NotNull. like @NotEmpty(message = "cannot be empty")

If any of the validations fail, ConstraintViolationException is thrown. Exception handling can be done to customise this exception and throw 400 Bad Request.

Upvotes: 2

Related Questions