Today
-
Yesterday
-
Total
-
  • Thymeleaf 와 Enum 클래스를 사용해서, html radio 태그 제어
    Spring Boot 🍃 2023. 12. 6. 00:01

    보고 배운 블로그 : taegyunwoo.github.io


    Lombok과 Thymeleaf 의존성을 추가한 상태라는 가정하에 진행 ✏️


    Enum 클래스 정의

    AnimalType

    @AllArgsConstructor
    @Getter
    public enum AnimalType {
        MONKEY("몽키 🐵"),
        PANDA("팬더 🐼")
        ;
    
        private String description;
    
    }

    Enum이 포함된 데이터 객체 생성

    AnimalDto

    @Getter @Setter
    @ToString
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public class AnimalDto {
    
        private String animalId; 
    
        private AnimalType animalType;
    
        public static AnimalDto of(AnimalType type) {
            return AnimalDto.builder()
                    .animalType(type).build();
        }
    
    }

    Controller 작성

    ZooController

    @Slf4j
    @Controller
    @RequestMapping("/zoo")
    public class ZooController {
    
        @ModelAttribute("animalTypes")
        public AnimalType[] animalTypes() {
            return AnimalType.values();
        }
    
        @GetMapping
        public String animalWritePage(Model model) {
            log.info("🚩 ======== zoo / animalWritePage 진입 ");
    
            model.addAttribute("item", AnimalDto.of(AnimalType.MONKEY));
            return "zoo";
        }
    }

    @ModelAttribute 에 대해 자세히 알려주는 블로그 : developer-joe.tistory


    html 작성

    zoo.html

    <html lang="ko" xmlns:th="http://www.thymeleaf.org">
    <head>	... </head>
    <body>
    
        <form method="post" action="/feeding" th:action th:object="${item}">   
    		
            <div th:each="type : ${animalTypes}">
                <input type="radio" th:field="*{animalType}" th:value="${type.name()}">
                <label th:for="${#ids.prev('animalType')}" th:text="${type.description}"></label>
            </div>
    	
    	</form>
        
    </body></html>

    1 . form 태그에 th:object="${변수명}" 을 작성해준다.

    <form th:object="${item}">  

    2 . div 태그에 th:each="type : ${데이터 정의 list}"를 작성해준다.

    <div th:each="type : ${animalTypes}">

    thymeleaf의 each 구문을 통해

    데이터 list의 값들을 전부 해석해서 div 태그로 구현해준다.


    thymeleaf에서 사용할 type이라는 변수를 생성해서

    list의 데이터를 하나씩 사용할 수 있다.


    th:each="type : ${animalTypes}"

    for(var type: animalTypes) 와 같음


    3 . radio 태그에 아래의 요소를 작성해준다.

    th:field="*{animalType}" th:value="${type.name()}"

    <input type="radio" th:field="*{animalType}" th:value="${type.name()}">
    • th:field에 들어가는 값은 form 태그에서 작성했던 object 변수의 필드 이름이다. *{} 기호를 사용하여, animalType 변수에 태그의 입력 값을 바인딩한다.

    - `th:value`에 들어가는 값은 type 변수에 저장된 데이터이다.

    th:field 의 값과, th:value의 값을 비교해서

    값이 같으면 checked=checked 를 생성해준다.


    4 . label 태그에 아래 요소를 작성해준다.

    th:for="${#ids.prev('animalType')}" th:text="${type.description}"

    <label th:for="${#ids.prev('animalType')}" th:text="${type.description}"></label>
    • th:for label 태그에서 주로 사용되며, label과 연관된 input 태그를 식별하기 위해 쓰인다.

    - `#ids.prev('animalType')`

    tymeleaf에서 제공하는 ids객체를 사용하기위해 작성된 문장이다. #을 붙여서 #ids. 형태로 사용하며, 요소의 id를 관리하는데 사용한다. #idx.prev() 는 현재 요소 이전에 처리 된 요소id생성한다.

    • th:text 에 들어가는 값은 태그 사이에 text 입력을 위해 사용된다.

    실행 확인

    http://localhost:8080/zoo

    같은 방식으로 checkbox 태그도 작성할 수 있는것으로 보았다.

    하지만 checkbox로 작성을 하면

    hidden 값도 생성되고 무언가 다른 부분이 생기는듯 해서 함께 정리하지 않았다.


    나중에 checkbox에 대해서 사용할 일이 있다면

    그 때 추가 🐢

Designed by Tistory / Custom by 얼거스