ModelAndView

Developer:Bird·2020년 11월 19일
0

Spring

목록 보기
1/17

1. ModelAndView란?

DisPatchServelt에 의해 처리될 뷰를 직접 지정할 수 있고 Model(entity)부분에 있는 데이터를 전달 할 수 있도록 합니다.

2. 코드 분석

-ModelAndView구조

public class ModelAndView {
    @Nullable
    private Object view;
    @Nullable
    private ModelMap model;
    @Nullable
    private HttpStatus status;
    private boolean cleared = false;
.
.
.

-ModelMap구조

public class ModelMap extends LinkedHashMap<String, Object> {
    public ModelMap() {
    }

    public ModelMap(String attributeName, @Nullable Object attributeValue) {
        this.addAttribute(attributeName, attributeValue);
    }

    public ModelMap(Object attributeValue) {
        this.addAttribute(attributeValue);
    }

    public ModelMap addAttribute(String attributeName, @Nullable Object attributeValue) {
        Assert.notNull(attributeName, "Model attribute name must not be null");
        this.put(attributeName, attributeValue);
        return this;
    }

다음과 같이 ModelAndView는 크게 view,model,status로 구성되어있다.
(1) view: view의 path를 담는다.
(2) model: ModelMap 자료형이며 ModelMap은 HashMap을 상속함으로써
Key,Value로 접근이 가능하다. 이때 Key는 Model이 가지고 있는 변수명이고 value는 값이 된다.
(3) status: status의 경우 https의 상태를 의미한다.

3. 예제

-Model부분

@Table(name = "owners")
public class Owner extends Person {

    @Column(name = "address")
    @NotEmpty
    private String address;

    @Column(name = "city")
    @NotEmpty
    private String city;

    @Column(name = "telephone")
    @NotEmpty
    @Digits(fraction=0,integer=10)
    private String telephone;

    @OneToMany(cascade=CascadeType.ALL,mappedBy="owner")
    private Set<Pet> pets;

-Controller부분

    @GetMapping("/owners/{ownerId}")
    public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
        ModelAndView mav = new ModelAndView("owners/ownerDetails");
        Optional<Owner> OptinalOwner = this.owners.findById(ownerId);
        Owner owner = OptinalOwner.get();
        for (Pet pet : owner.getPets()) {
            pet.setVisits((Set<Visit>) visits.findByPetId(pet.getId()));
        }
        mav.addObject(owner);
        return mav;
    }

- View부분

   <h2>Owner Information</h2>
  
    <table class="table table-striped" th:object="${owner}">
      <tr>
        <th>Name</th>
        <td><b th:text="*{firstName + ' ' + lastName}"></b></td>
      </tr>
      <tr>
        <th>Address</th>
        <td th:text="*{address}"></td>
      </tr>
      <tr>
        <th>City</th>
        <td th:text="*{city}"></td>
      </tr>
      <tr>
        <th>Telephone</th>
        <td th:text="*{telephone}"></td>
      </tr>
    </table>

다음과 같이 view에게 데이터를 전달할때 ModelAndView를 이용해서 Model,Path,Status 정보를 한번에 보낼 수 있게 만드는 것이 바로 ModelAndView이다.

#참고자료: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html

profile
끈임없이 발전하자.

0개의 댓글