Spring - validate input inside Controller against a bean

末鹿安然 提交于 2019-12-13 01:20:13

问题


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


来源:https://stackoverflow.com/questions/23618602/spring-validate-input-inside-controller-against-a-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!