// src/main/java/hello/hellospring/controller/HomeController.java
package hello.hellospring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
<!-- src/main/resources/templates/home.html -->
<div class="container">
<div>
<h1>Hello Spring</h1>
<p>회원 기능</p>
<p>
<a href="/members/new">회원가입</a>
<a href="/members">회원목록</a>
</p>
</div>
</div>
원래 아무것도 없으면 /
으로 들어갔을 때 static/index.html
이 뜨는데 여기서 컨트롤러 HomeController
를 만들어줬으니까 우선순위에 따라 static/index.html
이 아니라 templates/home.html
을 띄운다.
GET
: 폼 창 반환
// src/main/java/hello/hellospring/controller/MemberController.java
@Controller
public class MemberController {
@GetMapping("/members/new")
public String createForm() {
return "members/createMemberForm";
}
}
<!--src/main/resources/templates/members/createMemberForm.html-->
<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>
POST
: 회원 등록
// src/main/java/hello/hellospring/controller/MemberController.java
@Controller
public class MemberController {
@PostMapping("/members/new")
public String create(MemberForm form) {
Member member = new Member();
member.setName(form.getName());
memberService.join(member);
return "redirect:/";
}
}
// src/main/java/hello/hellospring/controller/MemberForm.java
public class MemberForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// src/main/java/hello/hellospring/controller/MemberController.java
@Controller
public class MemberController {
@GetMapping("/members")
public String list(Model model) {
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
}
}
<!--src/main/resources/templates/members/memberList.html-->
<html lang="en" xmlns="http://www/thymeleaf.org">
...
<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>
서버를 껐다가 켜면 다 사라져있다.
=> 디비 연동 해야함