我有一个 Spring Rest Web 服务。 Controller 类将 HTTP 请求中的参数映射到自定义请求对象。我的请求对象如下所示:
public class DMSRequest_global {
protected String userName = "";
protected String includeInactiveUsers = "";
protected String documentType = ""; And the getter and setter of the fields above
}
Spring 使用反射将传入请求中的值设置为该对象。我的问题是,我们是否可以使用注释或其他方法来验证上例中的 documentType 等字段,以仅接受来自以下列表的值:可接受的值,例如 {".doc", ".txt",".pdf"} 。如果请求中发送了其他值,spring 将抛出无效请求异常。
最佳答案
您可以编写自己的自定义 validator 。
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Contraint(validatedBy = DocumentTypeValidator.class)
@Documented
public @interface ValidDocumentType {
String message() default "{com.mycompany.constraints.invaliddocument}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] value();
}
还有一个自定义 validator 。
public class DocumentTypeValidator implements ConstraintValidator<ValidDocumentType, String> {
private String[] extenstions;
public void initialize(ValidDocumentType constraintAnnotation) {
this.extenstions = constraintAnnotation.value();
}
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if (object == null)
return true;
for(String ext:extenstions) {
if(object.toLowerCase().matches(ext.toLowerCase())) {
return true;
}
}
return false;
}
}
最后,您可以使用自定义注释来注释您的 Bean。
@ValidDocumentType({"*.doc", "*.txt","*.pdf"})
protected String documentType = "";
您可以在 post 中阅读更多相关信息。
关于java - Spring Rest Web 服务输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204359/