Loading...
Spring Framework Reference Documentation 7.0.2의 @ModelAttribute의 한국어 번역본입니다.
아래의 경우에 피드백에서 신고해주신다면 반영하겠습니다.
감사합니다 :)
@ModelAttributeSee equivalent in the Servlet stack
@ModelAttribute method parameter 어노테이션은 form 데이터, query 파라미터, URI path 변수, 그리고 request 헤더를 model 객체에 바인딩합니다. 예:
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2public String processSubmit(@ModelAttribute Pet pet) { } (1)Copied!
| 1 | Pet 인스턴스에 바인딩합니다. |
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2fun processSubmit(@ModelAttribute pet: Pet): String { } (1)Copied!
| 1 | Pet 인스턴스에 바인딩합니다. |
Form 데이터와 query 파라미터는 URI 변수와 헤더보다 우선하며, 동일한 이름의 request 파라미터를 오버라이드하지 않는 경우에만 URI 변수와 헤더가 포함됩니다. 헤더 이름에서 dash는 제거됩니다.
Pet 인스턴스는 다음과 같을 수 있습니다:
Model에 의해 추가되었을 수 있는 model에서 액세스됩니다.@SessionAttributes에 model attribute가 나열된 경우 HTTP 세션에서 액세스됩니다.기본적으로 생성자와 프로퍼티 데이터 바인딩이 모두 적용됩니다. 그러나 model 객체 설계에는 신중한 고려가 필요하며, 보안상의 이유로 웹 바인딩에 특화된 객체를 사용하거나 생성자 바인딩만 적용하는 것이 권장됩니다.
프로퍼티 바인딩을 여전히 사용해야 하는 경우, 어떤 프로퍼티가 설정될 수 있는지를 제한하기 위해 allowedFields 패턴을 설정해야 합니다. 이에 대한 자세한 내용과 예제 설정은 model design을 참조하십시오.
생성자 바인딩을 사용할 때는 @BindParam 어노테이션을 통해 request 파라미터 이름을 커스터마이즈할 수 있습니다. 예:
1class Account { 2 3 private final String firstName; 4 5 public Account(@BindParam("first-name") String firstName) { 6 this.firstName = firstName; 7 } 8}Copied!
1class Account(@BindParam("first-name") val firstName: String)Copied!
@BindParam은 생성자 파라미터에 해당하는 필드에도 위치할 수 있습니다.<br>@BindParam은 out of the box로 지원되지만,DataBinder에DataBinder.NameResolver를<br>설정하여 다른 어노테이션을 사용할 수도 있습니다.
생성자 바인딩은 List, Map, 그리고 배열 arguments를 지원하며, comma-separated 리스트와 같은 single 문자열에서 변환되거나, accounts[2].name 또는 account[KEY].name과 같은 인덱스 키를 기반으로 할 수 있습니다.
Spring MVC와 달리 WebFlux는 Mono<Account>와 같이 model에서 리액티브 타입을 지원합니다. 리액티브 타입 래퍼의 유무에 관계없이 @ModelAttribute argument를 선언할 수 있으며, 실제 값에 따라 적절히 resolve됩니다.
데이터 바인딩이 errors를 발생시키는 경우, 기본적으로 WebExchangeBindException이 발생하지만, 이러한 errors를 컨트롤러 메서드에서 처리하기 위해 @ModelAttribute 바로 다음에 BindingResult argument를 추가할 수도 있습니다. 예:
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) { (1) 3 if (result.hasErrors()) { 4 return "petForm"; 5 } 6 // ... 7}Copied!
| 1 | BindingResult를 추가합니다. |
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2fun processSubmit(@ModelAttribute("pet") pet: Pet, result: BindingResult): String { (1) 3 if (result.hasErrors()) { 4 return "petForm"; 5 } 6 // ... 7}Copied!
| 1 | BindingResult를 추가합니다. |
BindingResult argument를 사용하려면, 리액티브 타입 래퍼 없이 그 앞에 @ModelAttribute argument를 선언해야 합니다. 리액티브를 사용하려는 경우, 그 리액티브를 통해 errors를 직접 처리할 수 있습니다. 예:
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2public Mono<String> processSubmit(@Valid @ModelAttribute("pet") Mono<Pet> petMono) { 3 return petMono 4 .flatMap(pet -> { 5 // ... 6 }) 7 .onErrorResume(ex -> { 8 // ... 9 }); 10}Copied!
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2fun processSubmit(@Valid @ModelAttribute("pet") petMono: Mono<Pet>): Mono<String> { 3 return petMono 4 .flatMap { pet -> 5 // ... 6 } 7 .onErrorResume{ ex -> 8 // ... 9 } 10}Copied!
데이터 바인딩 이후에 validation을 자동으로 적용하려면 jakarta.validation.Valid 어노테이션 또는 Spring의 @Validated 어노테이션을 추가하면 됩니다 (Bean Validation 및 Spring validation 참조). 예:
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result) { (1) 3 if (result.hasErrors()) { 4 return "petForm"; 5 } 6 // ... 7}Copied!
| 1 | model attribute argument에서 @Valid를 사용합니다. |
1@PostMapping("/owners/{ownerId}/pets/{petId}/edit") 2fun processSubmit(@Valid @ModelAttribute("pet") pet: Pet, result: BindingResult): String { (1) 3 if (result.hasErrors()) { 4 return "petForm"; 5 } 6 // ... 7}Copied!
| 1 | model attribute argument에서 @Valid를 사용합니다. |
다른 파라미터에 @Constraint 어노테이션이 있어서 메서드 validation이 적용되는 경우, 대신 HandlerMethodValidationException이 발생합니다. 컨트롤러 메서드 Validation 섹션을 참조하십시오.
@ModelAttribute사용은 선택 사항입니다. 기본적으로,<br>BeanUtils#isSimpleProperty에 의해<br>simple value 타입이 아니고 AND 다른 argument 리졸버에 의해 resolve되지 않는<br>어떤 argument든 implicit@ModelAttribute로 처리됩니다.
GraalVM으로 네이티브 이미지를 컴파일할 때, 위에서 설명한 implicit
@ModelAttribute<br>지원은 관련 데이터 바인딩 리플렉션 힌트에 대한 적절한 ahead-of-time 추론을 허용하지<br>않습니다. 그 결과, GraalVM 네이티브 이미지에서 사용하기 위해서는 메서드 파라미터에<br>@ModelAttribute를 명시적으로 어노테이션하는 것이 권장됩니다.
@CookieValue
@SessionAttributes