본문 바로가기
dev/Spring

[Spring] ModelAttribute, BindingResult

by dev_Step 2022. 6. 4.

 

@ModelAttribute 

   >>적용 대상을 Model의 속성으로 자동 추가해주는 애너테이션으로, 반환타입 또는 컨트롤러 매서드의 매개 변수로 사용 가능

 

>> 즉 Model m  --> m.addAttribute() 해서 추가해주던것을 자동으로 해줌

 

 

>> 반환 타입 앞에서도 사용이 가능하다.

 

 

>>  http://localhost:8080/ch2/getYoilMVC5?year=2022&month=6&day=4 실행결과

>> model.addAttribute() 하지 않아도 model을 통해 전달되어 

>> browser 에서    2022 // 6 // 4 // 토  가 출력되는 것을 확인 할 수 있다.

 

 

 

 

컨트롤러 매개변수

1. 기본형 @RequsetParam    <-- 생략되어 있다고 생각하면되고

2. 참조형 @ModelAttribute     <--  참조형일 경우 생략 되어 있다고 생각하면된다.  즉 생략 해도 된다.

 

즉...

>> 4개의 표현식은 결과적으로 다 같은 말로

>> @ModelAttribute 가 없는경우에는 model에  참조형 변수의 맨 앞글자가 소문자로 myDate로 key값으로 들어가고 (@ModelAttribute("myDate") 가 생략되어 있음) 

>> Model을 매개변수로 추가해 주지 않아도 자동으로 추가되어 JSP로 넘어간다.

 

 

 

=================================================================================

 

WebDataBinder 

>> 웹에서 들어오는 요청을 1.타입변환, 2.데이터 검증하여 BindingResult에 저장하며

>> BindingResult는 매서드의 매개변수로써 확인할 수 있따.

@RequestMapping("/getYoilMVC5")
public String main(@ModelAttribute Mydate date, BindingResult result){
      // BindingResult result 는 참조형 타입 바로 뒤에 와야 한다.
}

매개변수 BindingResult를 통해서 결과를 확인 할 수 있따.

>> WebDataBinder 에 의해서

>> 1. 타입변환 2. 데이터 검증과정이 이루어 지는데 

ex)  http://localhost:8080/ch2/getYoilMVC6?year=2022&month=6&day=aa   일부러 오류를 만들어보면

>> BindingResult 에서 Error 가 발생한 것을 확인할 수 있다.

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'mydate' on field 'day': rejected value [aa]; 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: "aa"]

 

>>  BindingResult result  를 통해서 얻는결과

>>  BindingResult result  를 통해서 FieldError를 통해서 더 자세한 에러 코드를 확인 할 수 있따.

 

 

 

 

 

'dev > Spring' 카테고리의 다른 글

[Spring] 회원가입 페이지  (0) 2022.06.04
[Spring] Tomcat port 변경  (0) 2022.06.04
[Spring] RequestParam  (0) 2022.06.03
[Spring] Servlet의 발전과정을 탐구해보자 - 탐구단계  (0) 2022.05.22
[Spring] Private한 메서드 호출  (0) 2022.05.22