Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

방카@Dev

[Spring]Validator를 이용한 유효성 검사 본문

BackEnd/Spring

[Spring]Validator를 이용한 유효성 검사

방카킴 2024. 6. 17. 11:24

1. Validator 인터페이스 구현

public class StudentValidator implements Validator {

	@Override
	public boolean supports(Class<?> arg0) {
		// TODO Auto-generated method stub
		return Student.class.isAssignableFrom(arg0);
	}

	@Override
	public void validate(Object obj, Errors errors) {
		System.out.println("validate()");
		Student student = (Student)obj;
		
//      1번째 방법
		String studentName = student.getName();
		if(studentName == null || studentName.trim().isEmpty()) {
			System.out.println("studentName is null or empty");
			errors.rejectValue("name","trouble");
		}
		
		int studentId = student.getId();
		if(studentId == 0) {
			System.out.println("studentId is 0");
			errors.rejectValue("id","trouble");
		}
	}
}

 

2. ValidationUtils 객체 메서드 사용

public class StudentValidator implements Validator {

	@Override
	public boolean supports(Class<?> arg0) {
		// TODO Auto-generated method stub
		return Student.class.isAssignableFrom(arg0);
	}

	@Override
	public void validate(Object obj, Errors errors) {
		System.out.println("validate()");
		Student student = (Student)obj;

//      2번째 방법	
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name","trouble","studentName is null or empty");  
        //에러, 필드, 에러코드, 디폴트 에러메세지
		
		int studentId = student.getId();
		if(studentId == 0) {
			System.out.println("studentId is 0");
			errors.rejectValue("id","trouble");
		}
	}
}

3. @InitBinder를 이용한 초기화

<pom.xml>에 hibernate 추가

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.Final</version>
		</dependency>
        
        <!-- 오류 발생으로 인한 dependency 추가 -->
        <dependency>
		    <groupId>javax.xml.bind</groupId>
		    <artifactId>jaxb-api</artifactId>
		    <version>2.3.1</version>
		</dependency>
		<dependency>
		    <groupId>org.glassfish.jaxb</groupId>
		    <artifactId>jaxb-runtime</artifactId>
		    <version>2.3.1</version>
		</dependency>

 

@RequestMapping(value="/createDonePage", method=RequestMethod.POST)
public String studentCreate(@ModelAttribute("student")@Valid Student student, BindingResult result) {

    String page = "createDonePage";

//		StudentValidator validator = new StudentValidator();
//		validator.validate(student, result);

    if(result.hasErrors()) {
        page= "createPage";
    }
    return page;
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(new StudentValidator());
}