์์ ๊ตฌ์ฑํ MVC ํจํด์ ๋ง๊ฒ ํ์ ๊ฐ์ ๊ณผ ์กฐํ ๊ธฐ๋ฅ์ ๊ฐ๋ฐํ์๋ค.
https://github.com/jiholee0/hello-spring
Controller (controller/MemberController.java)
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(value = "/members")
public String list(Model model) {
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
}
}
View (templates/home.html)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<h1>Hello Spring</h1>
<p>ํ์ ๊ธฐ๋ฅ</p>
<p>
<a href="/members/new">ํ์ ๊ฐ์
</a>
<a href="/members">ํ์ ๋ชฉ๋ก</a>
</p>
</div>
</div> <!-- /container -->
</body>
</html>
View (templates/members/createMemberFrom.html)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<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> <!-- /container -->
</body>
</html>
View (templates/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> <!-- /container -->
</body>
</html>
Model (MemberForm.java)
package hello.hellospring.controller;
public class MemberForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
๋ฐ์ํ