在我的Student课程中,我有很多字段存储在数据库中,我还有一个字段来存储照片(因为我正在使用MultiPartFile数据类型),我正在使用自定义验证来验证这个字段。
以下是验证代码
@Component
public class PhotoValidator implements Validator{
@Override
public boolean supports(Class<?> clazz) {
return Student.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Student student=(Student)target;
if(student.getStudentPhoto()!=null){
if(student.getStudentPhoto().getSize()==0){
errors.rejectValue("file", "missing.file");
}
}
if(!student.getStudentPhoto().getOriginalFilename().endsWith(".jpg")){
errors.rejectValue("file", "invalid.file");
}
}
}
在控制器中我正在实现它
@InitBinder
protected void initBinderStudent(WebDataBinder binder) { binder.setValidator(photoValidator);
}
我的学生模特是: -
@Entity
@Table(name = "STUDENT")
public class Student extends UrlEntity {
@Transient
MultipartFile studentPhoto;
@Column(name = "COURSE_TYPE", nullable = false)
@NotNull(message = "Course Type: Course Type can not be left blank")
private in.jmi.constants.CourseType courseType;
@OneToOne(cascade = CascadeType.ALL, optional = false)
@JoinColumn(name = "STUDENT_USER")
@Valid
private User user;
这张照片的自定义验证无法正常工作,它也搞砸了我在这里进行的其他基于注释的验证。
我已经检查了stackoverflow中的很多帖子,但找不到与此特定问题的任何关系。
注意: - 如果我从控制器中删除验证代码,则代码可以正常执行它应该执行的所有验证。
答案 0 :(得分:0)
您正在混合示例中的方法。您没有在代码示例中显示导入,但PhotoValidator
类未实现Bean Validation约束。它可能是一些Spring / JSF特定的验证器!?
要实现Bean Validation约束,您需要定义约束注释,并且至少需要一个实现ConstraintValidator
。这些都在Creating custom constraints中描述。有很多例子可以编写自定义约束。