티스토리 뷰
1. 요청 파라미터 값을 검사하는 두 가지 방법
- 웹 브라우저 : 자바스크립트를 이용하여 데이터를 전송하기 전에 검사
- 웹 서버 : 전달받은 파라미터의 값을 검사
2. Command 객체 값 검증하기
jsp 에서 Taglib Directive 추가하여 form 에 관련된 태그 라이브러리 사용
기존의 form 태그를 form:form 으로 바꾼다. 이때 commandName을 추가해야한다. commandName 은 form의 ID이다.
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 |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 에러결과를 보기 위하여 taglib 추가 -->
<form:form commandName="loginVO" method="POST" action="/HelloMVC/doLogin">
<input type="text" name="id" />
<form:errors path="id" /><br/>
<input type="text" name="password" />
<form:errors path="password" /><br/>
<input type="text" name="memberNumber" />
<form:errors path="memberNumber" /><br/>
<!-- name path의 이름이 같아야 어떤것이 오류가 났는지 알 수 있다. -->
<input type="checkbox" name="enableAutoLogin" value="true" />
<input type="text" name="hobby" />
<input type="text" name="hobby" />
<input type="text" name="hobby" />
<input type="submit" />
</form:form>
</body>
</html> |
cs |
JSP 를 수정 한 후 DispatcherServlet을 수정한다.
Annotation으로 값을 검증하기 위하여 validator를 추가해야한다.
라이브러리가 분리되었으므로 먼저 pom.xml의 Dependencies 에서 validation과 자주 쓰이는 애노테이션을 제공하는 Hibernate Validator 를 추가한다.
이후 applicationContext.xml 에 validation을 자동으로 동작시키기 위하여
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> 를 추가한다.
이제 Model (Command 객체)를 수정한다. 값을 검증하기 위한 Annotation를 추가해야 한다.
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 |
package com.ktds.jmj.vo;
import java.util.List;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginVO {
@NotEmpty(message="ID는 필수 입력값 입니다.")
private String id;
@NotEmpty(message="PASSWORD는 필수 입력값 입니다.")
private String password;
//value가 default값이므로 그냥 적어도 된다.
// @Min(value=10) @Min(10)
@Min(value=10, message="숫자는 10이하를 적을 수 없습니다.")
@Max(value=50, message="숫자는 50이상을 적을 수 없습니다.")
private int memberNumber;
private boolean enableAutoLogin;
private List<String> hobby;
public List<String> getHobby() {
return hobby;
}
public void setHobby(List<String> hobby) {
this.hobby = hobby;
}
public boolean isEnableAutoLogin() {
return enableAutoLogin;
}
public void setEnableAutoLogin(boolean enableAutoLogin) {
this.enableAutoLogin = enableAutoLogin;
}
public int getMemberNumber() {
return memberNumber;
}
public void setMemberNumber(int memberNumber) {
this.memberNumber = memberNumber;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
cs |
다음으로 Controller를 수정, 이때 Valid 뒤에는 항상 Errors가 존재해야한다. ( 반드시 Valid 바로 뒤에 와야 한다. )
Errors는 이미 jsp에 보낼 데이터로 저장이 되어 있어 자동으로 model에 들어간다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
public ModelAndView doLogin(@Valid LoginVO loginVO, Errors errors, HttpSession session, HttpServletResponse response) {
//Valid 뒤에는 항상 Errors가 존재해야 한다. ( 반드시 Valid 뒤에 와야한다! )
//errors는 자동으로 model에 들어간다. 이미 jsp에 보낼 데이터로 저장이 되어 있다.
ModelAndView view = new ModelAndView();
if( errors.hasErrors() ) { // 발생된 에러가 있으면
view.setViewName("login/login"); //로그인 페이지로 이동
return view;
}
// 발생된 에러가 없다면 home으로 이동
view.setViewName("redirect:/home");
session.setAttribute("_MEMBER_", loginVO.getId());
return view;
} |
cs |
JSP에서 Form의 데이터가 전달되었을 때 @Valid 속성이 붙은 Command 객체는 내부의 Validation Annotation 을 체크한다.
그 결과는 Errors Command 객체에 저장되어 View에 전달된다.
전달된 Errors Command 객체는 jsp에서의 <form:errors path="id" />로 출력할 수 있고, 에러가 있을 때만 출력된다.
3. 주요 Annotation
Validaion의 주요 Annotation
Annotation |
주요 속성 |
설명 |
@NotNull |
|
값이 Null이면 안된다. |
@Size |
min , max |
min 부터 max 사이에 있는지 검사, 값이 null인 경우 유효한 것으로 판단 |
@Min @Max |
value : 값 |
|
@DecimalMin @DecimalMax |
value : 값 |
|
@Digits |
integer: 정수부분 숫자 길이 fraction : 소수부분 숫자 길이 |
숫자의 정수 부분과 소수 부분의 길이가 범위에 있는지 검사 |
@Pattern |
regexp : 정규 표현식 |
문자열이 지정한 패턴에 일치하는지 검사, 값이 null인 경우 유효한 것으로 판단 |
Hibernate Validator의 Annotation
Annotation |
주요 속성 |
설명 |
@NotEmpty |
|
String인 경우 빈 문자열이 아니여야 하고, 콜랙션이나 배열인 경우 크기가 1 이상 |
@NotBlank |
|
@NotEmpty와 동일 차이점 : String의 경우 뒤의 공백을 무시 |
@Length |
min, max |
문자열의 길이가 min과 max 사이에 있는지 검사 |
@Range |
min, max |
숫자 값이 min과 max 사이에 있는지 검사 |
|
|
값이 email 주소인지 검사 |
@URL |
|
값이 URL 인지 검사 |
'BackEnd > Spring' 카테고리의 다른 글
[Spring] Controller의 리턴 타입 (0) | 2016.04.15 |
---|---|
[Spring] 예외처리 (1) | 2016.04.14 |
[Spring] Redirect 처리 (0) | 2016.04.14 |
[Spring] Spring 기본 4 (MVC) (0) | 2016.04.12 |
[Spring] Spring 기본 3 (MVC) (0) | 2016.04.12 |
- Total
- Today
- Yesterday
- boj
- restfb
- algorithm
- BFS
- order by
- onPostExecute
- table
- Spring
- jsp
- 안드로이드 비콘
- onBackPressed
- 예외처리
- mybatis
- REDIRECT
- maven
- indexOf
- 안드로이드 스튜디오
- controller
- DFS
- sort
- list
- AlertDialog.Builder
- INSERT
- 이클립스
- DP
- Baekjoon Online Judege
- RequestMapping
- 자바
- servlet
- java
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |