반응형
package hello.hellospring.controller;
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";
}
}
▶ @GetMapping("/members") : localhost:8080/members로 접속하면 members 폴더에 있는 memberList.html 파일을 보여줌
▶ memberService에서 findMembers() 호출하여 전체 회원 목록을 불러와 members에 저장
▶ model.addAttribute("members", members) : html 파일에서 members를 사용
<!DOCTYPE html>
<html lang="kor" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>회원 조회</title>
</head>
<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>
▶ member는 members에서 받아온 리스트를 의미함
▶ localhost:8080/members에 접속하면 localhost:8080/members/new에서 회원가입한 이름이 순서대로 나옴
반응형
'Spring > inflearn' 카테고리의 다른 글
순수 JDBC (0) | 2022.09.03 |
---|---|
H2 데이터베이스 설치 (0) | 2022.09.02 |
회원 웹 기능 - 등록 (0) | 2022.08.31 |
회원 웹 기능 - 홈 화면 추가 (0) | 2022.08.30 |
자바 코드로 직접 스프링 빈 등록하기 (0) | 2022.08.29 |