홈 컨트롤러 추가
main/java/hello.hellospring/controller/HomeController
package hello.hellospring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/") // localhost:8080/
public String home(){
return "home";
}
}
회원 관리용 홈
main/java/resources/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>
static/index.html이 있는데 home.html로 연결되는 이유?
주소로 들어가면 내장 톰켓 서버는
지금은 컨트롤러가 있으므로 static에 있는 @Getmapping(”/”)에 들어가지 않는다.
회원 등록 폼 개발
회원 등록 폼 컨트롤러
main/java/hello.hellospring/controller/MemberController
@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";
}
}
회원 등록 폼 HTML
resources/templates/members/createMemberForm
<!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>
회원 등록 컨트롤러
웹 등록 화면에서 데이터를 전달 받을 폼 객체
main/java/hello.hellospring/controller/MemberForm
package hello.hellospring.controller;
public class MemberForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
회원 컨트롤러에서 회원을 실제 등록하는 기능
main/java/hello.hellospring/controller/MemberController
@PostMapping("/members/new")
public String create(MemberForm form){
Member member = new Member();
member.setName(form.getName()); // html form에서 받은걸 member의 name에 set
memberService.join(member);
return "redirect:/";
}
회원 컨트롤러에서 조회 기능
main/java/hello.hellospring/controller/MemberController
@GetMapping("/members")
public String list(Model model){
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
}
회원 리스트 HTML
resources/templates/members/memberList
<!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> <!--getId 접근 -->
<td th:text="${member.name}"></td> <!--getName 접근 -->
</tr>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>
참고
스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard