main/java/hello.hellospring/controller(package)/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";
}
}
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>
</div> <!-- /container -->
</body>
</html>
=> 회원 가입 클릭 시: ~/members/new
=> 회원 목록 클릭 시: ~/members
이전에 만든 index.html은 어디 갔을까?
main/java/hello.hellospring/controller(package)/MemberController.java 에 추가
@GetMapping("/members/new")
public String createForm(){
return "members/createMemberForm";
}
main/java/resources/templates/members(Directory)/createMemberForm.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>
-회원가입 페이지 생성까지 완료
-name이 key로 넘겨짐
-등록 버튼 누르면 post 방식으로 action="~"로 넘어감(MemberController에 PostMapping으로 이동)
main/java/hello.hellospring/controller(package)/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;
}
}
-MemberForm에 스프링이 getter, setter 이용해서 값을 넣어줌
main/java/hello.hellospring/controller(package)/MemberController.java 에 추가
@PostMapping("/members/new")
public String create(MemberForm form){
Member member=new Member();
member.setName((form.getName()));
memberService.join(member);
return "redirect:/"; //이름 입력 다한 후에 home 화면으로 돌려보냄
}
+Get:주로 조회, Post: 주로 데이터 보낼 때
main/java/hello.hellospring/controller(package)/MemberController.java 에 추가
@GetMapping(value = "/members")
public String list(Model model) {
List<Member> members = memberService.findMembers();
model.addAttribute("members", members);
return "members/memberList";
}
resources/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}"> //members 읽음(꺼내서 member에 담음), 루프 돌면서 실행
<td th:text="${member.id}"></td>
<td th:text="${member.name}"></td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>
-spring1, spring2 정상등록 확인가능
*현재는 서버 끄고 다시 켜면 데이터 모두 사라짐->데이터 저장해야 함.