[Spring] 스프링 입문 (코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술)

밀크야살빼자·2023년 4월 18일
0

회원 웹 기능 - 홈 화면 추가

controller/HomeController

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";
     }
     
}
<!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><!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>
  • controller가 정적 파일보다 우선순위가 높기 때문에 homeController가 먼저 실행된다.

회원 웹 기능 - 등록

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";
   }
   
   //등록
   @PostMapping(value = "/members/new")
   public String create(MemberForm form) {
        Member member = new Member();
        member.setName(form.getName());
        memberService.join(member);
        return "redirect:/";
   }
   
   //조회
   @GetMapping(value = "/members")
   public String list(Model model) {
        List<Member> members = memberService.findMembers();
        model.addAttribute("members", members);
        return "members/memberList";
   }
   
}

<!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>

회원 웹 기능 - 조회

<!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> <!-- /container -->
</body>
</html>
package hello.hellospring.controller;
public class MemberForm {
   private String name;
   public String getName() {
   	return name;
   }
   public void setName(String name) {
   	this.name = name;
   }
}
profile
기록기록기록기록기록

0개의 댓글