| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
- 서비스레이어
- 바인딩변수
- after-throwing
- SpringBoot
- 유효성검사
- 어노테이션
- frontController
- AOP
- 생성자주입
- gradle
- springjdbc
- c:if
- Java
- @RequestParam
- MVC
- spring
- PointCut
- .xml
- produces
- @ResponseBody
- application.properties
- @Valid
- 스프링
- 의존주입
- jointpoint
- @
- @RequestMapping
- 비즈니스레이어
- Model
- springmvc
- Today
- Total
메모장
Spring 유효성 검사 (3) 본문
저번 코드를 살펴 보자
@RequestMapping("/test") // method요청 써도됨 // @Valid 너 만들라고 시킨거 얘 검사할때 시키는거야
public String root(@Valid VO vo, BindingResult br, Model model) { // 커맨드 객체 , Model model , 에러친구 커맨드 객체로 받아올 수 있게
// 검사 코드가 컨트롤러에 그대로 오픈 되어 있지 않다 . 따로 검사 객체에 들어가있다.
// 서버 통신과 관련된 컨트롤러가 있고 검사만 진행하는 컨트롤러가 따로 있다 .
VOValidator voV = new VOValidator();
voV.validate(vo, br); // 검사를 했을때 검사 할게 여러가지 일 수 있는데 자바에서 그게 안되기 때문에 따로 객체를 사용할 수 있다. br 는 커맨드 객체(참조변수)를 참조하고 있다.
// validate 메서드 강제에 의해 만들어진 메서드
if(br.hasErrors()) {
System.out.println("로그 : 에러 발생함!");
System.out.println("발생한 에러목록");
System.out.println(br.getAllErrors()); //전체를 출력해준다. // for문과도 잘 어울림
if(br.getFieldError("id") != null) { // id에서 에러가 발생했을때
System.out.println(br.getFieldError("id").getCode());
}
if(br.getFieldError("password") != null) {
System.out.println(br.getFieldError("password").getCode());
// 어노테이션으로 설정한거 볼게
}
}
model.addAttribute("apple", vo.getId());
return "test";
}
저번 코드 에서 우리는 아직 한가지 걸리는 부분이 있다.

아직도 객체화를 직접 해주고 있다는 점 !
이것을 제어의 역행 == IoC 커맨드 객체화 시켜보자 !
먼저 gradle에서 설정 파일을 추가 하자

implementation 'org.springframework.boot:spring-boot-starter-validation' // validator 자동화 시키기
그리고 컨트롤러로 이동해서

메서드를 하나 만들어준다.
@InitBinder
: Spring Validator를 사용 시 @Valid 어노테이션으로 검증이 필요한 객체를 가져오기 전에 수행할 method를 지정해주는 어노테이션이다.
그리고

@Valid
: 객체 안에서 들어오는 값에 대해 검증이 가능해진다.
@InitBinder 와 @Valid 같이 쓰인다.
@InitBinder 는 컨트롤러가 동작했을때 이미 validator 가 동작 될 수 있도록 할때 사용하고
@Valid 는 검증 할려는 객체가 무엇인지 정해준다. 지금은 VO 객체 이기 때문에 VO 앞에 붙인다.
전체코드는 이러하다.
package com.hong.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.validation.Valid;
@Controller
public class CTRL {
@RequestMapping("/")
public String root() {
return "test";
}
@RequestMapping("/test") // method요청 써도됨 // @Valid 너 만들라고 시킨거 얘 검사할때 시키는거야
public String root(@Valid VO vo, BindingResult br, Model model) { // 커맨드 객체 , Model model , 에러친구 커맨드 객체로 받아올 수 있게
// VOValidator voV = new VOValidator(); // 얘를 직접 쓰고 있는데 이걸 없애보자 // 이걸 커맨드 객체화 IoC 시키고 있다.
// voV.validate(vo, br); // 검사를 했을때 검사 할게 여러가지 일 수 있는데 자바에서 그게 안되기 때문에 따로 객체를 사용할 수 있다. br 는 커맨드 객체(참조변수)를 참조하고 있다.
// validate 메서드 강제에 의해 만들어진 메서드
if(br.hasErrors()) {
System.out.println("로그 : 에러 발생함!");
System.out.println("발생한 에러목록");
System.out.println(br.getAllErrors()); // for문과도 잘 어울림
if(br.getFieldError("id") != null) {
System.out.println(br.getFieldError("id").getCode());
}
if(br.getFieldError("password") != null) {
System.out.println(br.getFieldError("password").getCode());
// 어노테이션으로 설정한거 볼게
}
}
model.addAttribute("apple", vo.getId());
return "test";
}
// 컨트롤러가 동작했을때 이미 validator 가 동작 될 수 있도록
@InitBinder // 이런 어노테이션을 사용하기 위해 gradle 에 추가 한거다.
protected void initBinder(WebDataBinder wdb) {
wdb.setValidator(new VOValidator());
}
}
하지만 이것도 예전 방식에는 이렇게 자주 보였으나 요즘은 바뀌었다.
왜냐하면 아직도 new 가 쓰이고 있기 때문이다.

Spring boot 유효성 검사 최종
요즘은 VO 에서 간편하게 유효성 검사를 처리한다.

어노테이션이 대충 짐작이 가실 수 있다.
@NotNull - null 일때 나올 message
@NotEmpty - Empty 일때 나올 message
@Size - min 부터 max 까지 , message
요즘 VO 에서 유효성 검사를 처리 하는게 보편적이다.
'Spring > 개념정리' 카테고리의 다른 글
| Spring boot [ DB 연결하기 ] (0) | 2024.09.03 |
|---|---|
| Spring boot 유효성검사 (2) 에러메세지 (0) | 2024.08.07 |
| Spring boot 유효성 검사 (1) (0) | 2024.08.07 |
| Spring boot 요청을 처리하는 방법 (0) | 2024.08.07 |
| Spring boot 의 static 폴더 (0) | 2024.08.07 |