【发布时间】:2016-03-27 08:32:30
【问题描述】:
在我的 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 中的许多帖子,但找不到与此特定问题的任何关系。
注意:-如果我从控制器中删除验证代码,则代码可以正常执行所有应执行的验证。
【问题讨论】:
标签: spring hibernate validation bean-validation