Spring - validate input inside Controller against

2019-08-02 03:50发布

问题:

I have a controller that uses payload to perform some actions, but now I would like to validate it before performing any operations. The payload is converted to byte[] and then read into a class called AuthorizationServer, which has some validation annotations - @NotNull, @NotBlank etc.

This is a block from the class AuthorizationServer:

@NotBlank
private String authorizationServerId;

@Property
@Indexed(unique = true)
@NotBlank
private String authorizationUrl;

@Property(policy = PojomaticPolicy.TO_STRING)
@NotBlank
private String clientAuthorizationUrl;

@NotBlank
private String deviceRootCert;

This is the controller:

byte[] bytes = IOUtils.toByteArray(request.getInputStream());
        String signature = authorization.split(":")[1];

        ObjectMapper mapper = objectMapper();
        AuthorizationServer authorizationServer = mapper.readValue(bytes, 
        AuthorizationServer.class);

Now, in the next line, I would like to validate the authorizationServer against the annotations declared in AuthorizationServer class. I am on Spring 4. Can someone please guide me? thanks!

回答1:

Why not just have spring unmarshal the AuthorizationServer class for you? Then you would just annotate it with @Valid and look at the BindingResult object for errors:

@RequestMapping(value = "/somUrl", method = RequestMethod.POST)
@ResponseBody
public void doSomething(@RequestBody @Valid AuthorizationServer authorizationServer, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
           //do something
        }

Update:

Try this code to programmatically validate:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<AuthorizationServer>> errors = validator.validate(authorizationServer);

Update 2:

What about this:

@Valid
AuthorizationServer authorizationServer = mapper.readValue(bytes, AuthorizationServer.class);