SPRING - Validator 를 이용한 form 데이터 값 검증

이번 글은 Validator을 이용해

form 데이터 값들을 검증 하겠습니다.

회원 가입을 할때 ID를 아무렇게나 입력하면

안되기 때문에 검증이 필요합니다


또한 form 태그를 이용해 데이터를 커맨드 객체에

담아 컨트롤 객체에 전달하는데 이때 커맨드

객체의 유효성 검사를 합니다.

자바스크립트를 이용한 것은 클라이언트에서

검사하는 방법이지만 지금 하려는 Validator 인터페이스를

이용하는 방법은 서버에서 검사하는 방법입니다.


먼저 form 태그를 사용할 jsp 파일 생성합니다

저는 createPage 라고했습니다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% 
    String conPath = request.getContextPath();
%>
<form action="student/create">
    이름 : <input type="text" name="name" value="${student.name}"> <br />
    아이디 : <input type="text" name="id" value="${student.id}"> <br />
    <input type="submit" value="전송"> <br />
</form>
</body>
</html>
cs


이제 action을 받아줄 컨트롤러 생성해줍니다


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
package com.spring.ex;
 
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class StudentController {
    @RequestMapping("/studentForm")
    public String studentForm() {
        return "createPage";
    }
    
    @RequestMapping("/student/create")
    public String studentCreate(@ModelAttribute("student") Student student, BindingResult result) {
        
        String page = "createDonePage";
        
        StudentValidator validator = new StudentValidator();
        validator.validate(student, result);
        if(result.hasErrors()) {
            page = "createPage";
        }
        
        return page;
    }
 
}
 
cs


16line 에 BindingResult 는 벨리데이션으로

유효성 검사를 했을때 에러가 있는지 없는지

결과값이 담기는 클래스입니다.

다음 26line 에서 return 해주는 page를 만들어줍니다

이름은 createDonePage.jsp 했습니다


1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
이름 : ${student.name } <br />
아이디 : ${student.id }
</body>
</html>
cs


다음 Student. 클래스만들어줍니다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.spring.ex;
 
public class Student {
 
    private String name;
    private int id;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
}
 
cs



다음 위에서 말한 Validator 클래스를 만들어줍니다


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
32
33
package com.spring.ex;
 
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
 
public class StudentValidator implements Validator{
 
    @Override
    public boolean supports(Class<?> arg0) {
        return Student.class.isAssignableFrom(arg0);  // 검증할 객체의 클래스 타입 정보
    }
    
    @Override
    public void validate(Object obj, Errors errors) {
        System.out.println("validate()");
        Student student = (Student)obj;
        
        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");
        }
    }
    
 
}
 
cs


6line을 보면 이 클래스는 Validator을 구현 하고있습니다


먼저 Validator 구현 방법을 알아보기 위해

8line~27line 까지 주석처리 해봅니다



그럼 위 이미지와 같이 클래스 이름에 오류가 뜹니다

저 오류는 Validator 을 구현할 메소드를 만들라는 오류입니다



클래스 이름에 마우스 커서를 갖다 대고있거나 6line 왼쪽 전구를 클릭해줍니다

다음 Add unimplemented methods 눌러 메소드

추가합니다 구현 메소드는 2개가 생깁니다



다음 위와같이 생긴2개의 메소드를 개발자가 구현을 하면됩니다.


다시 위 소스를 보겠습니다


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
32
33
package com.spring.ex;
 
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
 
public class StudentValidator implements Validator{
 
    @Override
    public boolean supports(Class<?> arg0) {
        return Student.class.isAssignableFrom(arg0);  // 검증할 객체의 클래스 타입 정보
    }
    
    @Override
    public void validate(Object obj, Errors errors) {
        System.out.println("validate()");
        Student student = (Student)obj;
        
        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");
        }
    }
    
 
}
 
cs


먼저 8line 은 검증할 객체(Student객체)의

클래스 타입을 명시해주는 겁니다.

그리고 14line 은 obj와 errors 2개의

파라미터를 받습니다 obj는 커맨드 객체가

이쪽으로 들어오는데 커맨드객체의 타입이

student에 대한 타입이 올지 member에대한

타입이 올지 모르기 때문에 Object로 받습니다

모든 클래스는 Object를 상속을 받고 있기 때문입니다

다음 에러가 발생하면 그 에러를

담고있을 errors 받습니다


다음 16line에서 obj에 어떤 타입들 있는지 모르지만

그 값을 내가 원하는 타입으로 캐스팅 해줍니다

(Student)obj 는 obj를 위에서만든 Student 클래스로

캐스팅 하는겁니다.


18line 은 form에서 입력한 이름데이터가

비어있는지 확인하는 겁니다. isEmpty같이

메소드앞에 is가 붙는경우 메소드의 기능은 보통

구분,비교 등의 기능을 가지고있습니다

다음 에러가 있을경우 errors에 name 이라는 이름으로

trouble 값을 담아줍니다.


24line은 ID가 비어있는지 확인합니다


이제 마지막으로 테스트를 해봅니다



주소는 studentForm 입력 해야합니다

컨트롤러에서 studentForm으로 받았기 때문입니다



위와같이 정상적으로 출력됩니다

아이디는 Student.java클래스에서

int 형으로했기 때문에 숫자 넣어줬습니다


다음 아이디를 아무것도 입력 하지않고

테스트 해보겠습니다




위와같이 콘솔창에서 오류 메세지를

확인 할수 있습니다



'SPRING' 카테고리의 다른 글

SPRING - @Valid 와 @InitBinder  (0) 2018.02.07
SPRING - ValidationUtils 클래스  (0) 2018.02.07
SPRING - 스프링에서 한글처리  (0) 2018.02.07
SPRING - GET, POST, @ModelAttribute  (0) 2018.02.07
SPRING - @RequestParam 어노테이션  (0) 2018.02.06

댓글

Designed by JB FACTORY