Certification/Spring(2V0-72.22, SCP)

View에 데이터 전송을 위한 Model 개념

엘호리스 2018. 10. 3. 17:20

※ @RequestMapping 어노테이션이 적용된 메소드의 파라미터나 리턴 타입으로 ModelAndView, Model, ModelMap, Map, 커맨드 객체 등을 이용해서 모델을 뷰에 전달


뷰에 전달되는 모델 데이터

- @RequestMapping 메소드가 ModelAndView, Model, Map을 리턴하는 경우 이들에 담긴 모델 데이터가 뷰에 전달

- 추가적으로 다음의 항목도 뷰에 함께 전달

* 커맨드 객체

* @ModelAttribute 어노테이션이 적용된 메소드가 리턴한 객체

* 메서드의 Map, Model, ModelMap 타입의 파라미터를 통해 설정된 모델

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package sp.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import sp.mvc.vo.UserVO;
 
 
@Controller
public class UserController {
 
    @ModelAttribute("popularFruit")
    public String[] refPopularFruit(){
        return new String[]{"사과""포도""수박""참외"};
    }
 
    @RequestMapping(value="/userForm.sp", method=RequestMethod.GET)
    public String userForm(){
        System.out.println("----- UserController.userForm() : GET -----");
        return "user/userForm";
    }
 
 
    @RequestMapping(value="/userSave.sp", method=RequestMethod.POST)
    public ModelAndView userSave(UserVO userVo, Model model){
    // public ModelAndView userSave(@ModelAttribute("userVo") UserVO userVo, Model model){ 
System.out.println("----- UserController.userSave() : POST -----");
        System.out.println("userInfo : " + userVo.toString());
        model.addAttribute("msg""SUCCESS"); 
        
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/userInfo");
        modelAndView.addObject("userVo", userVo);
        return modelAndView;
    }
 
    @RequestMapping("/userView.sp")
    public Model userView(){
        System.out.println("----- UserController.userView() -----");
        Model model = new ExtendedModelMap();
        model.addAttribute("msg""member info");
        return model;    
    }
 
}
 

cs



▦ Map, Model, ModelMap을 통한 모델 설정 방법

  • Map, Model, ModelMap 중 한 가지를 파라미터로 전달

  • Map, Model을 리턴

* Map, Model은 인터페이스 이므로 인터페이스를 구현한 클래스의 객체를 생성해서 리턴
  • @ModelAttribute("popularFruit") : @ModelAttribute 어노테이션이 적용된 메소드가 리턴한 객체

  • public ModelAndView userSave(UserVO userVo, Model model) : Model 파라미터, ModelAndView 리턴 타입

  • public ModelAndView userSave(@ModelAttribute("userVo") UserVO userVo, Model model) : @ModelAttribute 어노테이션, ModelAndView 리턴 타입

  • public Model userView() : Model 리턴 타입