π[Spring] @ModelAttribute μ λ
Έν
μ΄μ
.
1οΈβ£ @ModelAttribute
- 
@ModelAttributeλ Spring Frameworkμμ μ£Όλ‘ μ¬μ©λλ μ λ Έν μ΄μ μΌλ‘, Spring MVCμμ λͺ¨λΈ λ°μ΄ν°μ μμ² λ°μ΄ν°λ₯Ό λ°μΈλ©νκ±°λ, 컨νΈλ‘€λ¬μμ λ°νλ λ°μ΄ν°λ₯Ό λ·°μ μ λΉνλ λ° μ¬μ©λ©λλ€. - 
@ModelAttributeλ λ κ°μ§ μ£Όμ μ©λλ‘ μ¬μ©λ©λλ€. 
1οΈβ£ λ©μλ νλΌλ―Έν°μμ μ¬μ©(@ModelAttribute νλΌλ―Έν° λ°μΈλ©)
- 
@ModelAttributeλ₯Ό λ©μλ νλΌλ―Έν°μ μ μ©νλ©΄, Springμ μμ² νλΌλ―Έν° λλ νΌ λ°μ΄ν°λ‘λΆν° κ°μ²΄λ₯Ό μλμΌλ‘ μμ±νκ³ , κ·Έ κ°μ²΄μ νλλ₯Ό μμ² νλΌλ―Έν° κ°μΌλ‘ λ°μΈλ©ν©λλ€.- μ΄λ κ² μμ±λ κ°μ²΄λ 컨νΈλ‘€λ¬ λ©μλ λ΄λΆμμ μ¬μ©ν μ μμ΅λλ€.
 
 
μμ.
@Controller
public class UserController {
    
    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user) {
        // User κ°μ²΄λ νΌ λ°μ΄ν°λ‘λΆν° μλμΌλ‘ μμ±λκ³  λ°μΈλ©λ©λλ€.
        // μ΄μ  user κ°μ²΄λ₯Ό μ¬μ©ν  μ μμ΅λλ€.
        System.out.println("User Name: " + user.getName());
        return "registrationSuccess";
    }
}
- μ μμμμ 
@ModelAttributeλUserκ°μ²΄λ₯Ό νΌ λ°μ΄ν°λ‘λΆν° μμ±νκ³ ,name,emailλ±μ νλ μμ² νλΌλ―Έν° κ°μΌλ‘ λ°μΈλ©ν©λλ€. 
2οΈβ£ λ©μλμ μ¬μ©(@ModelAttribute λ©μλ)
- 
@ModelAttributeλ₯Ό λ©μλ λ 벨μ μ μ©νλ©΄, ν΄λΉ λ©μλλ 컨νΈλ‘€λ¬μ λͺ¨λ μμ² μ μ μ€νλμ΄, λ°νλ κ°μ²΄λ₯Ό λͺ¨λΈμ μΆκ°ν©λλ€.- μ΄ κ°μ²΄λ μ΄ν λ·°μμ μ¬μ©λ  μ μμ΅λλ€.
```java
@Controller
public class UserController { 
@ModelAttribute(βuserTypesβ)
public ListpopulateUserTypes() { // μ΄ λ©μλλ 컨νΈλ‘€λ¬μ λͺ¨λ μμ² μ μ μ€νλ©λλ€. // μ΄ λ¦¬μ€νΈλ λͺ¨λΈμ μΆκ°λμ΄ λ·°μμ μ¬μ©λ μ μμ΅λλ€. return Arrays.asList("Admin", "User", "Guest"); } @GetMapping(β/registerβ)
public String showRegistrationForm(Model model) {
model.addAttribute(βuserβ, new User());
return βregisterβ;
}
}
``` - μ΄ κ°μ²΄λ μ΄ν λ·°μμ μ¬μ©λ  μ μμ΅λλ€.
 - μ μμμμ 
populateUserTypes()λ©μλλ@ModelAttribute("userTypes")λ‘ μ μΈλμ΄, μ΄ λ©μλκ° λ°ννλ 리μ€νΈλuserTypesλΌλ μ΄λ¦μΌλ‘ λͺ¨λΈμ μΆκ°λ©λλ€.- μ΄ κ°μ λ·°(μ: JSP, Thymeleaf ν νλ¦Ώ λ±)μμ μ κ·Όν μ μμ΅λλ€.
 
 
3οΈβ£ @ModelAttribute μ μ£Όμ κΈ°λ₯ μμ½.
- 1. νλΌλ―Έν° λ°μΈλ© : ν΄λΌμ΄μΈνΈμ μμ² λ°μ΄ν°λ₯Ό κ°μ²΄λ‘ λ³ννκ³ , μ΄ κ°μ²΄λ₯Ό 컨νΈλ‘€λ¬ λ©μλμμ μ¬μ©νλλ‘ ν΄μ€λλ€.
 - 
2. λͺ¨λΈ μΆκ° : λ©μλμ λ°ν κ°μ λͺ¨λΈμ μΆκ°νμ¬, ν΄λΉ λ°μ΄ν°κ° λͺ¨λ  λ·°μμ μ¬μ©λ  μ μλλ‘ ν©λλ€.
    
- μ΄ λκ°μ§ κΈ°λ₯μ ν΅ν΄ 
@ModelAttributeλ Spring MVCμμ λ°μ΄ν° λ°μΈλ©κ³Ό λ·°μ μ λΉλλ λ°μ΄ν°μ κ΄λ¦¬λ₯Ό κ°μννλ λ° μ€μν μν μ ν©λλ€. 
 - μ΄ λκ°μ§ κΈ°λ₯μ ν΅ν΄