참치코더의 꿈 메모장

Thymeleaf / 단일 체크 박스, 다중 체크 박스 정리 본문

Spring

Thymeleaf / 단일 체크 박스, 다중 체크 박스 정리

참치깡 2026. 1. 19. 16:55
728x90

 

단일 체크박스 (Boolean 값)

 

- 하나의 체크박스

- true / false 값을 서버로 전달

- 약관 동의, 활성화 여부 같은 경우에 사용

- html만 사용했을때 체크 값을 누르면 true값을  back단에 전송하지만 체크 하지 않으면

  값이 아예 전송되지 않는다.

- Thymeleaf는 이 문제를 해결하기 위해 hidden input을 자동 생성한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// DTO 예시
 
@Getter @Setter
public class UserForm {
    private boolean agree;
}
 
// Thymeleaf
 
<form th:action="@{/submit}" th:object="${userForm}" method="post">
    <label>
        <input type="checkbox" th:field="*{agree}">
        약관에 동의합니다.
    </label>
 
    <button type="submit">전송</button>
</form>
 
// 실제로 렌더링되는 HTML
 
<input type="hidden" name="agree" value="on">
<input type="checkbox" name="_agree" value="on">
 
 
// 원래라면 체크한다면 true 체크하지 않는다면 false가 반환되지만 타입리프가 내부 기능으로 hidden input을 넣어줘서 false를 
// 반환해준다.
 
 
cs

 

 

- th:field 사용시 hidden input이 자동 생성된다.

- 서버에서 항상 값이 보장된다.

 

다중 체크박스 (컬렉션 값)

 

- 여러 개의 체크박스 중 복수 선택

- List, Set 같은 컬렉션으로 값 수신

- 관심사, 기술 스택 선택 등에 사용

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// DTO 예시
 
@Getter @Setter
public class UserForm {
    private List<String> skills;
}
 
// 컨트롤러에서 옵션 전달
 
@GetMapping("/form")
public String form(Model model){
    model.addAttribute("userForm"new UserForm());
    model.addAttribute("skills", List.of("Java""Spring""React""Docker"));
    return "form";
}
 
<form th:action="@{/submit}" th:object="${userForm}" method="post">
 
    <div th:each="skill : ${skills}">
        <label>
            <input type="checkbox"
                   th:field="*{skills}" // 다중 선택시 선택한  자동으로 List / Set에 매핑
                   th:value="${skill}"> // 각 체크박스가 가지는 실제 값 ("Java", "Spring") 등등
            <span th:text="${skill}"></span>
        </label>
    </div>
 
    <button type="submit">전송</button>
</form>
cs

 

- 다중 체크박스도 마찬가지로 spring이 내부적으로 input hidden 값을 넣어줘서 True, False가 나오게 

  만들어 준다.

 

728x90
Comments