본문 바로가기
Back End/Spring

Spring - 웹 MVC 예제 (회원 조회)

by SolaBreeze 2023. 7. 4.

Model addAttribute(String name, Object value)

- value 객체를 name 이름으로 추가한다. 뷰 코드에서는 name으로 지정한 이름을 통해서 value를 사용한다.

Model addAttribute(Object value)

- value를 추가한다. value의 패키지 이름을 제외한 단순 클래스 이름을 모델 이름으로 사용한다. 이 때 첫 글자는 소문자로 처리한다.

- value가 배열이거나 컬렉션인 경우 첫 번째 원소의 클래스 이름 뒤에 "List"를 붙인 걸 모델 이름으로 사용한다. 이 경우에도 클래스 이름의 첫자는 소문자로 처리한다.

출처: https://devlogofchris.tistory.com/53

 

회원조회 컨트롤러

    @GetMapping("/members")
    public String list(Model model){
        //모든 멤버를 끌어올 수 있음
        List<Member> members = memberService.findMembers();
        model.addAttribute("members", members);
        return "members/memberList";
    }

memberList.html을 찾아서 반환해준다.

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
    <div>
        <table>
            <thead>
            <tr>
                <th>#</th>
                <th>이름</th>
            </tr>
            </thead>
            <tbody>
<!--            th:each는 th의 반복문 Loop이다.-->
            <tr th:each="member : ${members}">
                <td th:text="${member.id}"></td>
                <td th:text="${member.name}"></td>
            </tr>
            </tbody>
        </table>
    </div>
</div> <!-- /container -->
</body>
</html>
  • ${members}와 같이 되어있는것은 모델안에 있는 값을 꺼내 읽어드리는것이다.
  • th : each는 th의 반복문 Loop이다.