웹개발/Spring Boot

[Spring Boot] Model ModelAndView 차이점

08genie 2023. 6. 11. 11:16
반응형

Model  예제

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;

@Controller
RequestMapping("/model")
public String sampleModel(Model model)
{
  model.addAttribute("nickName", "08genie");
  
  return "temp/model";
}
  • 파라미터 방식
  • String 형태로 return
  • 값을 넣을 때 addAttribute()를 사용

 


ModelAndView 예제

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
@RequestMapping("/modelAndView")
public ModelAndView sampleModelAndView()
{
   ModelAndView mv = new ModelAndView();
   mv.addObject("nickName", "08genie");
   
   mv.setViewName("temp/modelAndView");
  
   return mv;
}
  • 컴포넌트 방식
  • 객체 형태로 리턴
  • 값을 넣을 때 addObject() 사용
  • Model 과 View를 합쳐 놓은 것으로 setViewName()으로 보낼  View를 세팅

 


💡 ModelAndView는 @Controller를 이용하기 전부터 사용했지만, Spirng MVC가 @Controller annotation을 지원하기 시작한 이후로 ModelAndView는 잘사용하지 않는다고 합니다.

 

Reference : https://develop-im.tistory.com/10 

https://javaoop.tistory.com/56

 

반응형