섹션 5: 회원 관리 예제 - 웹 MVC 개발

MineeHyun·2024년 7월 5일
0

회원 웹 기능 - 홈 화면 추가

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>
</body>
</html>
  • 이전 강의에서 만든 index.html이 static 폴더에 있지만, home.html을 보여준다.
  • 왜냐면 탐색에 우선순위가 있기 때문...!!!!!
  • 스프링 컨테이너에 @Controller - @GetMapping("/")로 넣어두었기 때문에, 이 친구 (home.html)을 먼저 읽고 찾는다. (이미 찾았으니 static 폴더를 뒤질 필요가 없다.)
  • 그래서 index.html이 있는데도 @GetMapping("/") 되어 있는 home.html을 띄워 준다.
  • @GetMapping("/")는 localhost:8080 뒤에 아무것도 없을 때 보여줄 것을 지정한다.
  • 신기한 것 1가지: 위에 올린 코드에서는 수정했는데, 두 번째 href를 <a href="members"> 이라고 썼었다.
  • 근데 이렇게... localhost:8080/members로 잘 감. (/가 없답니다)

회원 웹 기능 - 등록

  <!DOCTYPE HTML>
<html>

<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>
</body>
</html>
  • 위에서 "/"를 빼먹어도 direct가 잘 된다고 신기해했지만... 안되는 상황을 겪어버렸다
  • :<form action="members/new" method="post">와 같이 썼더니, return "redirect:/"했을 때 /members/members/new로 간다.
  • 왜지...?

--

form action -> button을 누르면 post 방식으로 데이터를 보낸다.
Mapping 두 가지의 url은 같지만 Post 방식으로 보냈기 때문에 PostMapping이 받는다.

PostMapping과 GetMapping
http에서 웹에 접근하는 방법

  • Post는 주로 데이터를 폼에 넣어서 전달할 때
  • Get은 조회할 때 주로 쓴다
  • html의 input으로 들어온 name을 form.setName으로 MemberForm 타입의 객체 (form)의 name 필드에 넣어준다 (스프링이~)
    • 이거 어떻게 이렇게 되는 건지 잘 이해가 안 됨... form action ... 때문일까?
  • 그렇게 setName()한 것을 getName으로 꺼내서 member의 setName의 parameter로 쓴다
  • 그리고 join 시킴!

회원 웹 기능 - 조회

<!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>
  • 타임리프가 본격적으로 동작을 합니다잉

  • 템플릿 엔진이 렌더링을 해줌 th:each로 loop를 돌면서 각각에 대해서 member.id와 member.name을 출력해줌 (members는 member.findAll()했기 때문에 모든 member를 가지고 있음)

알게 된 사실

  • 벨로그 마크다운에서 별 두 개 (**)는 bold고, 별 세 개 (***)는 bold and italic이다.
  • html의 form 이야기: HTML 폼(form) 이해

0개의 댓글