DataBinder(아주 간략)

2022. 2. 6. 15:54Spring 기초

브라우저를 통해 요청받은 값이, 실제 객체에 바인딩 될 때, DataBinder가 중간 역할을 해준다.

 

1. 타입 변환 --> 2. 데이터 검증을 한 뒤 BindingResult를 Controller에 전달하는 방식이다.

 

 역할을 살펴보기 위해

public static String main(MyDate date, BindingResult result)  throws Exception{
//이처럼 key 값을 생략할 경우 타입(MyDate)의 첫 글자를 소문자로 한 값이 key로 자동 저장된다.
System.out.println("result="+result);

...

...

}

코드를 위와 같이 작성하였다. 이후 url로 쿼리스트링을 전달할 때, day에 숫자가 아닌 'ㅁㅁ'을 입력하였다.

그러나,, form태그와 같이 요청하는 것이 아니라 url로 직접슈팅을 때렸더니 controller까지 값이 전달되지 못하고

예외처리에서 걸려버렸다.

따라서 예외처리를 해주는 메서드에 BindingResult를 매개변수로 추가한 뒤 콘솔에 찍어보았다.

@ExceptionHandler(Exception.class)
public String catch(Exception ex, BindingResult result){
return "yoilError";
System.out.println("result=" + result)
}

Field error in object 'myDate' on field 'day': rejected value [ㅁㅁ]; codes [typeMismatch.myDate.day,typeMismatch.day,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [myDate.day,day]; arguments []; default message [day]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'day'; nested exception is java.lang.NumberFormatException: For input string: "ㅁㅁ"]result=org.spri...

 

 

DataBinder에 바로 걸리는 모습이다.

'Spring 기초' 카테고리의 다른 글

스프링 웹 개발 방식 - 정적컨텐츠, MVC 패턴, API  (0) 2022.02.16
Cookie & Session  (0) 2022.02.09
@ModelAttribute, @RequestParam  (0) 2022.02.06
WAS(Web Application Server)와 Tomcat  (0) 2022.02.05
HTTP 요청과 응답 GET/POST  (0) 2022.02.05