본문 바로가기

Programming/Spring

Spring boot 시작하기 - 9강(조회)

반응형

1. @GetMapping("/members") 구현

MemberController에 @GetMapping("/members")를 구현합니다.

package hello.hellospring.controler;

import hello.hellospring.domain.Member;
import hello.hellospring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class MemberController {

    private final MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService){
        this.memberService = memberService;
    }

    @GetMapping("/members/new")
    public String createForm(){
        return "members/createMemberForm";
    }

    @PostMapping("/members/new")
    public String create(MemberForm form){
        Member member = new Member();
        member.setName(form.getName());

        memberService.join(member);

        return "redirect:/";
    }

    @GetMapping("/members")
    public String list(Model model){
        List<Member> members = memberService.findMembers();
        model.addAttribute("members", members);
        return "members/memberList";
    }
}

2. members/memberList.html 구현

컨트롤러 리턴값 정의부분에 따라 members/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>
                <tr th:each="member : ${members}">
                    <td th:text="${member.id}"></td>
                    <td th:text="${member.name}"></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>

 

<결과>

 

이름에  spring1, spring2를 입력할 경우 "회원 목록"클릭시 아래 우측과 같은 결과가 나오게 됩니다.

 

~~ 끝 ~~

반응형