6. Thymeleaf와 스프링 연계

한승록·2024년 8월 18일
0

스프링 부트 기초

목록 보기
6/6
post-thumbnail
※ 인프런 김영한님 강의를 본인의 이해를 바탕으로 작성한 글이므로 사용법에 틀린 부분이 존재할 수 있습니다.

1. 기능 종류

  1. SpringEL 문법 통합
  2. 스프링 빈 직접 호출
  3. 편리한 폼 관리를 위한 추가 속성
    • th:object
    • th:field, th:errors, th:errorclass
  4. 폼 컴포넌트 기능
    • checkbox, radio, List등을 편리하게 사용 가능
  5. 메시지, 국제화 기능
  6. 검증, 오류 처리 통합
  7. 변환 서비스 통합



2. 기능 구현

1) form

  • 구성

    • th:object, th:field 사용
          <form action="result" th:object="${object}" method="post">
            <!-- 순수 HTML -->
            <input type="text" id="itemName" class="form-control" name="itemName">
    
            <!-- 타임리프 구성 -->
            <!-- id와 name은 해당 변수명으로 value는 변수명에 해당하는 값을 렌더링 시 생성 -->
            <input type="text" class="form-control" th:field="${object.objectName}" />
            <input type="text" class="form-control" th:field="*{objectName}" />
            <!-- *을 붙여줌으로써 th:object로 설정해준 변수 이름 생략가능 -->
    
            <!-- 렌더링 후 결과 -->
            <!-- value에는 현재 값이 없기때문에 빈값으로 표현 -->
            <input type="text" class="form-control" id="objectName" name="objectName" value="" />
          </form>

2) 체크박스

  • 단일 체크 박스

    • 순수 HTML

          <form>
            <input type="checkbox" id="check" name="check" class="form-check-input" />
          </form>
      • 백엔드에서 해당 코드를 확인하게 되면 check를 하였을 경우 on이라는 값이 check를 하지 않을 경우 null이 전송
        -> null이 전송된다고 하기 보다는 아예 해당 값이 파라미터로 전송되지 않음
    • 해결 방안

        <!-- 방안 1) -->
        <form>
          <input type="checkbox" id="check" name="check" class="form-check-input" />
          <input type="hidden" name="_check" value="on" />
        </form>
      • '언더바'를 포함한 같은 이름의 name 속성을 추가하여 value에 on을 추가해주면 check하지 않을 경우 false값을 전달
            <!-- 방안 2) -->
            <!-- 타임리프 구성 -->
            <form th:object="${object}">
              <input type="checkbox" th:field="*{check}" class="form-check-input" />
            </form>
      
            <!-- 렌더링 후 결과 -->
            <!-- 방안 1)의 hidden 값을 자동 생성 -->
            <!-- checkbox 클릭 안했을 경우 -->
            <input type="text" class="form-control" id="check" name="check" value="true" /><input type="hidden" name="_check" value="on" />
            <!-- checkbox 클릭 했을 경우 -->
            <input type="text" class="form-control" id="check" name="check" value="true" checked="checked" /><input type="hidden" name="_check" value="on" />
      • hidden 필드를 자동 생성
  • 멀티 체크 박스

      <!-- 순수 HTML -->
    <form>
      <input type="checkbox" id="check1" name="check" class="form-check-input" />
      <input type="checkbox" id="check2" name="check1" class="form-check-input" />
      <input type="checkbox" id="check3" name="check2" class="form-check-input" />
    </form>
    
    <!-- 타임리프 구성 -->
    <form th:object="${object}">
      <div th:each="checkValue : ${checkList}" class="form-check form-check-inline">
        <input type="checkbox" th:field="*{check}" th:value="${checkValue.value}" class="form-check-input" />
      </div>
    </form>
    <!-- 서버에서 model로 전달 했을 경우를 가정 -->
    
    <!-- 렌더링 후 결과 -->
    <input type="text" class="form-control" id="check1" name="check" value="true" /><input type="hidden" name="_check" value="on" />
    <input type="text" class="form-control" id="check2" name="check" value="true" /><input type="hidden" name="_check" value="on" />
    <input type="text" class="form-control" id="check3" name="check" value="true" /><input type="hidden" name="_check" value="on" />
    <!-- th:field는 loop를 통해 생성되는 경우 자동으로 필드 변수명 뒤에 1,2,3과 같이 중복되지 않도록 생성 -->

3) 라디오 버튼

      <!-- 타임리프 구성 -->
      <form th:object="${object}">
        <div th:each="radioValue : ${radioList}" class="form-check form-check-inline">
          <input type="radio" th:field="*{radios}" th:value="${checkValue.value}" class="form-check-input" />
        </div>
      </form>

      <!-- 렌더링 후 결과 -->
      <!-- 1번을 선택했을 경우 -->
      <div class="form-check form-check-inline">
        <input type="radio" class="form-control" id="radios1" name="radios" value="해당 값" checked="checked" />
        <input type="radio" class="form-control" id="radios2" name="radios" value="해당 값" />
        <input type="radio" class="form-control" id="radios3" name="radios" value="해당 값" />
      </div>
      <!-- radio는 checkbox와 다르게 하나만 선택이 가능 -->
      <!-- 최초 선택 후에는 하나의 값은 선택이 되어 넘어오기 때문에 hidden이 필요 없음 -->

4) 셀렉트 박스

  <!-- 타임리프 구성 -->
  <form th:object="${object}">
    <select th:field="*{selectList}" class="form-check form-check-inline">
      <option value="">== 선택 ==</option>
      <option th:each="selectValue : ${selectValues}" th:value="${selectValue.value}" th:text="${selectValue.name}"></option>
    </select>
  </form>
출처 : [스프링 MVC 2편 - 백엔드 웹 개발 활용 기술](인프런)
profile
개발 학습

0개의 댓글