gpt4 book ai didi

java - 未在 Spring Controller 中执行验证

转载 作者:行者123 更新时间:2023-12-01 17:51:24 25 4
gpt4 key购买 nike

我想在类中使用注释。我用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com