본문 바로가기

프로그래밍/Spring Boot

Spring Boot_Model과 ModelAndView

반응형

Model 객체

: view의 이름을 String으로 return 하는 방법

1
2
3
4
5
6
7
8
9
10
11
@GetMapping("/faqList")
public String faqListPage(Model model,
        @RequestParam(name = "categoryId", defaultValue = "1", required = false) Integer categoryId) {
    
    List<FaqResponseDto> faqResponseDtos = faqService.readFaqByCategoryId(categoryId);
    
    model.addAttribute("faqResponseDtos", faqResponseDtos);
    
    return "/faq/faqList"
    
}
cs

ModelAndView 객체

: 데이터와 view를 동시에 설정하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
@GetMapping("/faqList")
public ModelAndView faqListPage(@RequestParam(name = "categoryId", defaultValue = "1", required = false) Integer categoryId) {
 
    ModelAndView mv = new ModelAndView();
    List<FaqResponseDto> faqResponseDtos = faqService.readFaqByCategoryId(categoryId);
    
    mv.addObject("faqResponseDtos", faqResponseDtos); // 뷰로 보낼 데이터 값
    mv.setViewName("/faq/faqList"); // 뷰의 경로
    
    return mv; // ModelAndView 객체를 반환
    
}
cs

 

Model은 데이터만 저장하고, ModelAndView는 데이터와 이동하고자 하는 View Page를 같이 저장한다는 차이점만 있고 내부적으로 작동하는 원리는 같다. 

반응형