我有一个使用有效负载执行某些操作的控制器,但现在我想在执行任何操作之前验证它。有效负载转换为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.有人可以指导我吗?谢谢!
答案 0 :(得分:0)
为什么不让Spring为您解组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);