简体   繁体   中英

Spring - validate input inside Controller against a bean

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM