[英]How to write custom validation in rest api?
在春季啟動。 我想進行字段驗證,如果輸入在數據庫中不存在,則返回錯誤。 我正在嘗試為多個輸入字段編寫自定義注釋。 控制器如下
@RestController
@Api(description = "The Mailer controller which provides send email functionality")
@Validated
public class SendMailController {
@Autowired
public SendMailService sendemailService;
org.slf4j.Logger logger = LoggerFactory.getLogger(SendMailService.class);
@RequestMapping(method = RequestMethod.POST, value = "/sendMail", consumes = {MediaType.TEXT_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, produces = {"text/xml", "application/json"})
@ResponseBody
@Async(value = "threadPoolTaskExecutor")
@ApiOperation("The main service operation which sends one mail to one or may recipient as per the configurations in the request body")
public Future<SendMailResult> sendMail(@ApiParam("Contains the mail content and configurations to be used for sending mail") @Valid @RequestBody MailMessage message) throws InterruptedException {
SendMailResult results = new SendMailResult();
try {
sendemailService.sendMessages(message);
long txnid = sendemailService.createAudit (message);
results.setTxnid (txnid);
results.setStatus("SUCCESS");
} catch(MessagingException | EmailServiceException e) {
logger.error("Exception while processing sendMail " + e);
results.setStatus("FAILED");
// TODO Handle error create results
e.printStackTrace();
} catch(Exception e) {
logger.error("Something went wrong " + e);
results.setStatus("FAILED");
// TODO Handle error create results
e.printStackTrace();
}
return new AsyncResult<SendMailResult>(results);
}
}
一個與請求映射的DTO
public class MailContext {
@NotNull
private String clientId;
@NotNull
private String consumer;
public int getClientId() {
return Integer.parseInt(clientId);
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String toJson() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String writeValueAsString = mapper.writeValueAsString(this);
return writeValueAsString;
}
}
請求xml
<mailMessage>
<mailContext>
<clientId>10018</clientId>
<consumer>1</consumer>
</mailContext>
</mailMessage>
如果這些在數據庫中不存在,則發送錯誤消息,否則調用服務方法。
請提出如何編寫帶有錯誤的自定義注釋。
我知道另一種驗證方法。 在控制器內部,您可以注冊驗證器。
@InitBinder
public void setup(WebDataBinder webDataBinder) {
webDataBinder.addValidators(dtoValidator);
}
例如,其中dtoValidator是Spring Bean的實例,該實例必須實現org.springframework.validation.Validator。
因此,您只需要實現兩個方法:supports()和validate(Object target,Errors errors);
在supports()方法中,您可以執行任何決定對象是否應由此驗證器驗證的操作。 (例如,您可以創建一個WithClientIdDto接口,如果被測試的對象是AsAssignableFrom(),則可以執行此驗證。或者,您可以使用反射檢查是否將自定義注釋顯示在任何字段上)
例如:(AuthDtoValidator.class)
@Override
public boolean supports(Class<?> clazz) {
return AuthDto.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
final AuthDto dto = (AuthDto) target;
final String phone = dto.getPhone();
if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(dto.getEmail())) {
errors.rejectValue("email", "", "The phone or the email should be defined!");
errors.rejectValue("phone", "", "The phone or the email should be defined!");
}
if (!StringUtils.isEmpty(phone)) {
validatePhone(errors, phone);
}
}
更新:您可以做到。
創建一個注釋,例如:
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = ClientIdValidator.class)
@Documented
public @interface ClientId {
String message() default "{some msg}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
並實現此驗證器:
class ClientIdValidator implements ConstraintValidator<ClientId, Long> {
@Override
public boolean isValid(Long value, ConstraintValidatorContext context) {
//validation logc
}
}
您可以在這里找到更多詳細信息: https : //reflectoring.io/bean-validation-with-spring-boot/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.