Thymeleaf) form형식에서 Enum type 값 받기

Dokuny·2021년 12월 25일
0

HTML form 태그에서 타임리프로 직접 th:value="${enum}" 이런 식으로 컨트롤러에서 Enum데이터를 받아서 찍어주고

controller에서 데이터를 enum타입 변수로 받으면 된다.

test.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="UTF-8">
		<title>test</title>
	</head>
	<body>
		<form action="/test" method="post">
			<select th:name="name">
				<option th:each="genre : ${genres}" th:value="${genre}" th:text="${genre.getValue()}"></option>
			</select>
			<input type="submit" value="등록">
		</form>
	</body>
</html>

TestController.class

@RequestMapping("/test")
@Controller
public class TestController {

    @GetMapping
    public String test(Model model) {
        model.addAttribute("genres",GenreName.values());
        return "test";
    }

    @PostMapping
    public String testPost(@ModelAttribute("testDto") TestDto testDto) {
        System.out.println(testDto.getName().getClass()); //enums.GenreName
        System.out.println(testDto.getName()); // DRAMA 
        return "/";
    }
}

GenreName.class

@Getter
@RequiredArgsConstructor
public enum GenreName {
    DRAMA("drama","드라마"),
    FANTASY("fantasy","판타지"),

    private final String key;
    private final String value;

TestDto.class

@Data
public class TestDto {

    private GenreName name;

}
profile
모든 것은 직접 경험해보고 테스트하자

0개의 댓글