春天 - 验证里面输入控制器对一个bean(Spring - validate input insi

2019-10-20 03:06发布

我有一个使用有效载荷来执行一些操作的控制器,但现在我想执行任何操作之前验证它。 有效载荷转换为byte[]然后读入到称为AuthorizationServer类,它有一些验证注释- @NotNull,@NotBlank等

这是从类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;

这是控制器:

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

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

现在,在下一行,我想验证对在AuthorizationServer类中声明的注解authorizationServer。 我在春天4.是否有人可以指导我? 谢谢!

Answer 1:

为什么不只是有春天解组为您AuthorizationServer类? 然后,你就只是@Valid标注它,并期待在BindingResult对象的错误:

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

更新:

试试这个代码以编程方式验证:

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

更新2:

那这个呢:

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


文章来源: Spring - validate input inside Controller against a bean