@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
<!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>
클라이언트가 요청하는 데이터와 일치하는 것이 컨트롤러에 있는지 먼저 확인한다. (static 파일보다 우선순위가 높다.)
@Controller
public class MemberController {
private final MemberService memberService;
@Autowired
public MemberController(MemberService memberService) {
this.memberService = memberService;
}
@GetMapping(value = "/members/new")
public String createForm() {
return "members/createMemberForm";
}
@GetMapping(value = "/members")
// 데이터를 조회할 때 씀.
public String list(Model model) {
List<Member> members = memberService.findMembers(); // 모든 멤버 불러오기
model.addAttribute("members", members);
return "members/memberList";
}
@PostMapping(value = "/members/new")
// 데이터를 폼에 넣어서 전달할 때 씀.
public String create(MemberForm form) {
Member member = new Member();
member.setName(form.getName());
memberService.join(member); // join()는 정보 보내는 함수임
return "redirect:/";
}
}
}
<!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>
<!-- th:each문에 의해 루프를 돌면서 템플릿 언어가 모델에서 members의 정보를 찾음.-->
</tr>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>