/*HomeController*/
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
/*MemberController*/
@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:/";
}
}
/*memberForm*/
public class MemberForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<!--templates/home.html-->
<body>
<div class="container">
<div>
<h1>Hello Spring</h1>
<p>회원 기능</p>
<p>
<a href="/members/new">회원 가입</a>
<a href="/members">회원 목록</a>
</p>
</div>
</div>
</body>
<!--templates/members/createMemberForm.html-->
<body>
<div class="container">
<form action="/members/new" method="post">
<div class="form-group">
<label for="name">이름</label>
<input type="text" id="name" name="name" placeholder="이름을 입력하세요">
</div>
<button type="submit">등록</button>
</form>
</div>
</body>
1 ) home 화면에서 회원가입 버튼 클릭
<a href="/members/new">회원 가입</a>
members/new를 GET 방식으로 호출
2 ) MemberController에서 GetMapping 맵핑
@GetMapping("/members/new")
public String createForm(){
return "members/createMemberForm";
}
templetes/members/createMemberForm으로 이동
3. submit 버튼을 통해 post 방법으로 "name" 데이터 전송
<form action="/members/new" method="post">
<input type="text" id="name" name="name" placeholder="이름을 입력하세요">
@PostMapping("/members/new")
public String create(MemberForm form){
Member member = new Member();
member.setName(form.getName());
memberService.join(member);
return "redirect:/";
}
/*MemberController*/
@Controller
public class MemberController {
private final MemberService memberService;
@Autowired
public MemberController(MemberService memberService){
this.memberService = memberService;
}
...
@GetMapping("/members")
public String list(Model model){
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
<!--templates/members/memberList.html-->
<body>
<div class="container">
<div>
<table>
<thead>
<tr>
<th>#</th>
<th>이름</th>
</tr>
</thead>
<tbody>
<!-- h:each가 loop를 돌면서 logic 실행 , Java의 for:each 구문이랑 비슷 -->
<tr th:each="member : ${members}">
<!-- getId, getName 접근 -->
<td th:text="${member.id}"></td>
<td th:text="${member.name}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>