[Thymeleaf] 타임리프 - 기본문법2

Harry park·2022년 6월 7일
0

Thymeleaf

목록 보기
3/3
post-thumbnail

📌 타임리프(Thymeleaf) 기본 문법2

기본문법 1 : 기본 기능과, text, utext, href, layout

📖 2) 기능

✍ 2-3) Form

💻 예시

<form th:action="@{/join}" th:object="${joinForm}" method="post">
  <label for="userId" class="form-check-label">Id</label>
  <input type="text" 	 id="userId" 	   th:field="*{userId}">
  <input type="password" id="userPassword" th:field="*{userPassword}">
</form>

📎 th:action="@{}"

👉 form 태그 사용시, 해당 경로로 요청을 보낼 때 사용

📎 th:object="${}"

👉 DTO 클래스의 객체라고 생각하면 된다.(submit 될 때 전송되어야 할 객체 데이터)

📎 th:field="*{}"

👉 th:field을 이용한 사용자 입력 필드는 id, name, value 속성 값이 자동으로 매핑된다.

🎈 th:objectth:field는 Controller에서 특정 클래스의 객체를 응답 받은 경우에만 사용 가능하다.

✍ 2-4) 조건문과 반복문

📖 조건문

📎 th:if="${}", th:unless="${}"

👉 Java에서의 if~else와 동일한 속성이다.
👉 th:ifth:unless는 동일한 조건을 지정하여야 한다.
💻 예시

<span th:if="${userNum} == 1"></span> 
<span th:unless="${userNum} == 2"></span>

📎 th:switch="${}", th:case="#{}" / th:case="'문자'"

👉 Java와 동일한 기능을 하는 속성이다.

💻 예시

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

📖 반복문

<tbody>
    <tr th:each="board : ${boardList}">
        <td><span th:text="${board.no}"></span></td>
        <td><span th:text="${board.title}"></span></td>
        <td><span th:text="${board.writer}"></span></td>
        <td>
          <span th:text="${#temporals.format(board.updateTime, 
                         'yyyy-MM-dd HH:mm:ss')}">
          </span>
      </td>
    </tr>
</tbody>

✍ 2-5) 기본 객체들

: ${#request}, ${#response}, ${#session}, ${#servletContext}, ${#locale

: 외의 객체

  • HTTP 요청 파라미터 접근: param
    예) ${param.파라미터key}
  • HTTP 세션 접근: session
    예) ${session.세션KEY}
  • 스프링 빈 접근: @
    예) ${@빈이름.메소드(필요시 매개변수)}

개인적으로 공부하며 기록한 내용으로, 틀린 내용이 있는 경우 덧글을 달아주시면 감사하겠습니다. 😍

profile
Jr. Backend Engineer

0개의 댓글