HTML form 태그에서 타임리프로 직접 th:value="${enum}" 이런 식으로 컨트롤러에서 Enum데이터를 받아서 찍어주고
controller에서 데이터를 enum타입 변수로 받으면 된다.
<!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>
@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 "/";
}
}
@Getter
@RequiredArgsConstructor
public enum GenreName {
DRAMA("drama","드라마"),
FANTASY("fantasy","판타지"),
private final String key;
private final String value;
@Data
public class TestDto {
private GenreName name;
}