회원 생성
Contorller
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class MemberController {
private final MemberService memberService;
@Autowired //스프링 컨테이너에서 MemberService를 의존성 주입해줌
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:/";
}
}
@PostMapping
: url을 form에 담아서 보낼 때
- html의 input 태그의 name값에 따라 컨트롤러 메소드의 파라미터의 객체 필드에 값이 들어옴 (스프링이 setter를 통해서)
DTO
package hello.hellospring.controller;
public class MemberForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- html의 input 태그의
name="name"
이므로 post 방식으로 넘어올 때 위 클래스 객체의 필드에 값이 들어감 (spring이 setter로 넣어줌)
회원 조회
Controller
@GetMapping("/members")
public String list(Model model){
List<Member> members = memberService.findMembers();
model.addAttribute("members",members);
return "members/memberList";
}
View
<!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>
</body>
</html>
- 모델에서 넘겨받은 리스트에서 각 멤버에 접근하면서 출력함
${member.id}
는 member의 getId()
를 통해 id를 얻는것임