타임리프 폼 처리

Updated:     Updated:

Categories:

Tags: , ,

입력 폼 처리

  • 객체 지정
    th:object="${변수명}" 
    

    컨트롤러에서 모델에 사용할 객체를 담아서 폼에 넣어주면, 타임리프에서 폼에서 사용할 객체를 지정할 수 있다. 또한, 선택 변수 식을 적용할 수 있다.

    *{변수 식}, *{name}, *{age} 
    
  • 필드 생성

th:field는 id, name, value 속성을 자동으로 만들어 준다. th:field = “*{생성할 필드 이름}”


단일 체크박스

  • 일반적인 HTML 체크박스
<div class="form-check">
<input type="checkbox" id="open" name="open" class="form-check-input"> 
<label for="open" class="form-check-label">판매 오픈</label>
</div>

위의 체크박스 코드에서는 input 태그에 value 값이 없으니 이름/값 쌍을 open=on으로 값을 제출한다. 스프링은 on이라는 값을 타입 컨버터를 통해 true로 바꾸어 전송해 준다. 만약 체크하지 않는다면 open이라는 필드 값 자체가 넘어가지 않는다. 이는 서버에서 값이 참인지 거짓인지를 판단할 때 값이 null이므로 오류가 날 여지가 많다

  • 히든필드 추가
    <input type="hidden" name="_open" value="on"/> 
    

    히든필드를 추가해 체크가 되어있다면 open=on&_open=on 값이 넘어오고 _open값은 무시된다. 체크가 되어있지 않다면 _open=on 값만 넘어오게 되는데, 이 경우 open값을 false로 처리한다.

  • 타임리프로 히든 체크박스 생략하기

타임리프를 사용하면 체크 박스의 히든 필드와 관련된 부분도 함께 해결해준다.

<input type="checkbox" id="open" th:field="*{open}" class="form-check-input">

또한 th:field를 사용하면 값이 있으면 checked표시를 타임리프가 알아서 해준다.


멀티 체크박스

  • 중복되는 객체 재사용하기

    @modelAttribute를 사용하면 해당 컨트롤러에서 요청할 때 regions에서 반환한 값이 자동으로 model에 담기게 된다.

@ModelAttribute("regions")
    public Map<String, String> regions(){
        Map<String, String> regions = new LinkedHashMap<>();
        regions.put("SEOUL", "서울");
        regions.put("BUSAN", "부산");
        regions.put("JEJU", "제주");
        return regions;
    }

폼을 만들때에는 th:each를 통해 iteration을 시켜주고, 각각의 값마다 체크박스를 만들어 주면 된다. label에는 input id값이 필요한데, 이는 타임리프에서 제공하는 #ids를 통해 생성된 id값을 가져올 수 있다.

<div th:each="region : ${regions}" class="form-check form-check-inline">
<input type="checkbox" th:field="${item.regions}" th:value="${region.key}" class="form-check-input" disabled>
<label th:for="${#ids.prev('regions')}" th:text="${region.value}" class="form-check-label"></label>
</div>

라디오 버튼

라디오 버튼은 여러 선택지 중에 하나를 선택할 때 사용할 수 있다. enum타입으로 상품 종류를 만든 뒤, values()를 통해 모든 정보를 배열로 반환할 수 있다. 멀티 체크박스와 마찬가지로 th:each를 통해 만들 수 있다.

 
      <div th:each="type : ${itemTypes}" class="form-check form-check-inline">
          <input type="radio" th:field="*{itemType}" th:value="${type.name()}" class="form-check-input">
          <label th:for="${#ids.prev('itemType')}" th:text="${type.description}" class="form-check-label"></label>
      </div>
 

셀렉트 박스

셀렉트 박스도 위와 마찬가지로 th:each를 통해 option태그들을 생성해주면 된다.

<select th:field="*{deliveryCode}" class="form-select"> 
<option value="">==배송 방식 선택==</option>
<option th:each="deliveryCode : ${deliveryCodes}" th:value="${deliveryCode.code}" th:text="${deliveryCode.displayName}"></option>
      </select>

spring 카테고리 내 다른 글 보러가기

Leave a comment