• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

@ModelAttribute에 관한 설명에 대한 질문이 있습니다.

20.01.28 10:21 작성 조회수 354

0

@ModelAttrubte를 사용하면 파라미터로 넘어오는 값들을 취합해서 객체로 바인딩 해주신다 설명하셨는데 제가 기존에 알고 있던 지식과 달라 질문드립니다.

@ModelAttribute는 해당 파라미터를 Model 객체에 Attribute로 추가(Model 객체가 없을 시 생성 후 추가)하는것이고

DataBinder가 파라미터로 넘어오는 값들을 취합해 객체로 만들어 주는것으로 알고있습니다.

제가 알고있는것이 맞나요..?

참조:  스프링 레퍼런스

답변 6

·

답변을 작성해보세요.

2

둘 다 맞아요. @ModelAttribute를 어떤 객체를 리턴하는 메소드에 사용하면 말씀하신 용도로 쓰이고 메소드 매개변수에 사용하면 제가 설명한대로 쓰이는거구요.

0

최진환님의 프로필

최진환

질문자

2020.01.28

어.. 그럼 정리하면 @ModelAttribute는 Simple한 값이 아니면 기본적으로 붙고

모델 객체의 속성으로 해당 객체를 넣어주는 어노테이션이다.

맞을까요?

0

저한테 레퍼런스 설명이 맞냐고 물으시는건가요.. 당연히 맞죠.

제가 수업에서 설명했던거 같은데 @RequestParam이랑 @ModelAttribute는 생략할 수 있습니다. 그걸 안쓰고 바인딩 받을 수 있다고 해서 @ModelAttribute에 그런 기능이 없는게 아니에요. 

Note that use of
 @ModelAttribute is optional — for example, to set its attributes. By default, any argument that is not a simple value type( as determined by BeanUtils#isSimpleProperty) and is not resolved by any other argument resolver is treated as if it were annotated with @ModelAttribute.

 

0

최진환님의 프로필

최진환

질문자

2020.01.28

더 아래로 가보면

After the model attribute instance is obtained, data binding is applied. The WebDataBinder class matches Servlet request parameter names (query parameters and form fields) to field names on the target Object. Matching fields are populated after type conversion is applied, where necessary. For more on data binding (and validation), see Validation. For more on customizing data binding, see DataBinder.

라고 되어있고 @ModelAttribute가 없어도 WebDataBinder를 통해 파라미터가 매핑되고 @ModelAttribute는 정확히는 파라미터가 매핑된 객체를 모델 객체의 속성에 넣어주는것. 맞나요?

@ModelAttribute를 사용하지않아도 데이터는 객체로 바인딩 되는것을 확인했습니다.

0

제대로 찾으셨네요. 거기에 바로 이렇게 적혀 있자나요. 바로 아래 예제도 나오구요. 

You can use the @ModelAttribute annotation on a method argument to access an attribute from the model or have it instantiated if not present. The model attribute is also overlain with the values of query parameters and form fields whose names match to field names. This is referred to as data binding, and it saves you from having to deal with parsing and converting individual query parameters and form fields. The following example binds an instance of Pet:


0

최진환님의 프로필

최진환

질문자

2020.01.28

기선님 혹시 죄송한데 관련된 자료 부탁드려도 괜찮을까요?

레퍼런스 에서 조금 유사한 내용이 있기는 한데.. 그건  모델(Model클래스 )을 객체화 한다는것으로 이해했습니다.

@ModelAttribute의 주석에서도 비슷한 내용은 못찾아서...