我想在类中使用注释。我用javax.validation.constrants.*
用于注释。
public final class EmailCredential implements Serializable {
private static final long serialVersionUID = -1246534146345274432L;
@NotBlank(message = "Sender must not be empty.")
@Email
private final String sender;
@NotBlank(message = "Subject must not be empty.")
private final String subject;
/// getters setters
}
它们都没有按预期工作。这意味着当调用下面的 API 时,如果注释字段无效,注释应该抛出错误。看起来没有注释来检查字段。在普通类中如何正确使用注释?
Controller :
@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Object> emailCredentials(@RequestBody EmailCredential emailCredential) {
return emailService.setCredentials(emailCredential);
}
最佳答案
在您的情况下,必须指定要触发的验证。
因此添加 @Valid
您要验证的参数上的注释,例如:
import javax.validation.Valid;
// ...
@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Object> emailCredentials(@RequestBody @Valid EmailCredential emailCredential) {
return emailService.setCredentials(emailCredential);
}
关于java - 未在 Spring Controller 中执行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49753594/