IT/개발자 면접

Spring MVC Model

Collin 2023. 12. 17. 08:55
반응형

 

 

1. org.springframework.ui.Model:

  • 사용 시점:
    • Controller에서 View로 데이터를 전달할 때 사용.
    • 메서드의 매개변수로 선언하여 데이터를 추가하거나 수정할 수 있음.
  • 설명:
    • Controller에서 View로 데이터를 전달하기 위한 인터페이스.
    • addAttribute(String attributeName, Object attributeValue) 메서드를 사용하여 데이터를 추가.
  • 장단점:
    • 장점:
      • 간단하게 데이터를 전달할 때 사용하기 편리.
    • 단점:
      • 유연성이 상대적으로 부족함.
@Controller
public class MyController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("message", "Hello, World!");
        return "exampleView";
    }
}

 

 

2. @ModelAttribute:

  • 사용 시점:
    • Controller 메서드의 매개변수로 선언하여, 해당 메서드가 호출될 때 데이터를 바인딩하거나 초기화할 때 사용.
  • 설명:
    • Controller 메서드의 특정 매개변수에 @ModelAttribute 어노테이션을 사용하여 해당 객체를 자동으로 바인딩하고 초기화.
    • 주로 폼 데이터를 받아오거나 초기화할 때 사용.
  • 장단점:
    • 장점:
      • 폼 데이터를 객체에 자동으로 매핑하여 편리하게 사용 가능.
    • 단점:
      • Model의 유연성보다는 특정 객체에 종속적인 방식.

 

@Controller
public class MyController {
    @GetMapping("/form")
    public String form(Model model) {
        model.addAttribute("myObject", new MyObject());
        return "formView";
    }

    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute("myObject") MyObject myObject) {
        // 폼 데이터가 자동으로 MyObject에 매핑됨.
        // 이후 로직 처리
        return "resultView";
    }
}

 

차이점과 장단점:

  • 차이점:
    • org.springframework.ui.Model은 Controller에서 View로 데이터를 전달하는 인터페이스.
    • @ModelAttribute는 Controller 메서드의 특정 매개변수에 사용하여 해당 객체를 초기화하고 데이터를 바인딩하는 용도로 사용.
  • 장단점:
    • org.springframework.ui.Model은 간단한 데이터 전달에 용이하지만 유연성이 부족할 수 있음.
    • @ModelAttribute는 특정 객체에 데이터를 바인딩하여 폼 데이터를 효과적으로 처리할 수 있지만, 해당 객체에 종속적인 방식.
반응형

'IT > 개발자 면접' 카테고리의 다른 글

Spring Security 암호화 방식  (0) 2023.12.16
Redis 란?  (0) 2023.12.15
마이크로서비스(Microservices)  (0) 2023.12.14
Git Flow 와 GitHub Flow , Branch 전략  (0) 2023.12.13
Java Checked Exception과 Unchecked Exception  (0) 2023.12.12